gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:26:21 26 4
gpt4 key购买 nike

在我的 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”。

我该如何继续?

最佳答案

您可以将目标添加到 UITextFieldUIControlEvent.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!)
}

关于iOS:当用户点击时将字符添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com