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

时间:2018-09-21 20:13:28

标签: swift uitextfield uitextfielddelegate

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

tf.stack

但是当键盘上的输入为#时,firsrt字符为nil,因此应该以什么方式使所有单词都以#开头并以,分隔,

1 个答案:

答案 0 :(得分:0)

您可以更轻松地在编辑更改的控制事件后检查文本,并在用户在每个单词后键入一个空格时清理字符串。您可以将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())
    }
}