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

how to add a string after each comma in 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 那么应该如何实现所有单词都以 # 开头并以 ,

分隔

您可以在编辑更改的控件事件后更轻松地检查文本,并在用户在每个单词后键入 space 时清理您的字符串。您可以将 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{![=10=].isEmpty}           // filtering empty components
                .map{ "#" + [=10=] + ", " }        // 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())
    }
}