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

iOS:在用户点击时向字符串添加字符,ios,swift,uitextfield,Ios,Swift,Uitextfield,在我的Swift 4应用程序中,我希望在textField中添加一个特殊字符,同时用户点击textField中的第二个字符 这就是我所做的: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == self.specialTextField {

在我的
Swift 4
应用程序中,我希望在
textField
中添加一个特殊字符,同时用户点击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”


我怎样才能继续

您可以为
uicontrol事件向
UITextField
添加目标。编辑更改的
事件以完成您想要的:

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!)
}

我相信你的
editingChanged
方法应该是这样的:
@objc func editingChanged(textField:UITextField){if textField==self.specialTextField{if textField.text?.count==2{self.specialTextField.text!+=“|”}
@EnriqueBermúdez不需要检查哪个textfield正在调用该方法,因为只有一个字段在调用it@LeoDabus如何允许删除“|”?因为它被
editingChanged
阻止。我的意思是,当用户想要删除字段中的值时,可以将UITextField子类化并实现deleteBackward methodHi@LeoDabus,您能帮我解决这个问题吗?