![](/img/trans.png)
[英]Cursor goes to end after setting text to UITextField inside shouldChangeCharactersIn
[英]shouldChangeCharactersIn Combined with Suggested Text
我有一个UITextField
并正在使用委托方法func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
此处的字段可以显示建议的文本(例如名称)。 问题出在建议被接受时和用户键入单个字母时。 如果采纳建议(例如Tom),则将触发委托方法,但string
仅包含空格“”。 这会导致验证失败,因为假定现实中他们选择一个完整的单词时,用户会在空白区域中键入内容。
我们如何使用shouldChangeCharactersIn
检查文本输入,但仍允许使用建议的文本?
如果用户使用建议,则shouldChangeCharactersIn
最多触发两次:第一次使用单个空格。 然后,如果该方法返回false
其他任何事情都不会发生。 但是,如果该方法返回true
则shouldChangeCharactersIn
会触发更多带有结尾的字符串+空格的事件。 因此,如果要使用键盘建议,则必须允许空格,并且(如果需要)以后根据需要以某种方式将其删除。 一种方法是使用这样的defer
(未经测试,但可以给您一个想法):
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == " " {
defer {
if let text = textField.text, let textRange = Range(range, in: text) {
textField.text = text.replacingCharacters(in: textRange, with: "")
}
}
return true
}
// rest of the code for input filtering
return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.