iOS:在用户点击时将字符添加到字符串

iOS: add char to string while user is tapping

在我的 Swift 4 应用程序中,我想在 textField 中添加一个特殊字符,同时用户点击文本字段中的第二个字符。

这是我所做的:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == self.specialTextField {
            if textField.text?.count == 2 {
                self.specialTextField.text! += "|"
            }
        }
        return true
    }

问题是“|”当我写第二个字符时不是直接添加而是与第三个字符同时添加。

例如:我会写"abcd".

我点击 "ab" 时没有任何反应。就在我点击 "c" 时,我得到 "ab|c".

我该如何进行?

您可以在 UITextField 中为 UIControlEvent.editingChanged 事件添加一个目标来完成您想要的:

specialTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)

并实现 editingChanged 选择器方法:

@objc func editingChanged(_ textField: UITextField) {
    // check the contents of your textField and insert the special characters as needed
    print(textField.text!)
}