如何在 UITextfield 中的每个逗号后添加一个字符串



我寻找一种使用 swift 在 uiTextField 中编写的每个单词的开头添加 # 的方法,我尝试使用此代码进行检查

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if  textField.text!.first != "#" {
print(textField.text!.first)
print(textField.text!)
textField.text = ""
}
}

但是当键盘上的输入为 # 时,第一个字符为 nil,所以应该有什么方法来实现所有单词都以 # 开头并用 ,

您可以更轻松地在编辑更改控件事件后检查文本,并在用户在每个单词后键入空格时清理字符串。你可以对UITextField进行子类化,它应该看起来像这样:

class TagsField: UITextField, UITextFieldDelegate {
override func didMoveToSuperview() {
delegate = self
keyboardType = .alphabet
autocapitalizationType = .none
autocorrectionType = .no
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
prepareString()
if text!.hasSuffix(", #") { text!.removeLast(3) } // clean the residue on end
resignFirstResponder()
return false
}
func prepareString() {
text = text!.components(separatedBy: CharacterSet.letters.inverted)   // filtering non letters and grouping words
.filter{!$0.isEmpty}           // filtering empty components
.map{ "#" + $0 + ", " }        // add prefix and sufix to each word and append # to the end of the string
.string + "#" 
}
override func deleteBackward() {
let _ = text!.popLast()    // manually pops the last character when deliting
}
@objc func editingChanged(_ textField: UITextField) {
if text!.last == " " {
prepareString()
} else if !text!.hasPrefix("#") {  // check if the first word being typed has the # prefix and add it if needed.
text!.insert("#", at: text!.startIndex)
}
}
}

extension Collection where Element: StringProtocol {
var string: String {
return String(joined())
}
}

最新更新