shouldChangeCharactersIn 结合建议文本 [英] shouldChangeCharactersIn Combined with Suggested Text
问题描述
我有一个 UITextField
并且正在使用委托方法 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) ->布尔
I have a UITextField
and am using the delegate method func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
此处的字段可以显示建议的文本(例如名称).问题是在采纳建议与用户输入单个字母时出现的.如果采纳了建议(例如 Tom),则委托方法会触发,但 string
仅包含一个空格".这会导致验证失败,因为假设用户在现实中选择了一个完整的单词时正在空白处输入.
The fields here have the ability to display suggested text (e.g. name). The problem comes in when a suggestion is taken versus when the user types in single letters. If a suggestion is taken (e.g. Tom) the delegate method fires but string
just contains a blank space " ". This causes validation failure since it is assumed the user is typing in an empty space when reality they selected a full word.
我们如何使用 shouldChangeCharactersIn
来检查文本输入但仍然允许使用建议文本?
How can we use shouldChangeCharactersIn
to check text entry but still allow for the use of suggested text?
推荐答案
如果用户使用建议,shouldChangeCharactersIn
最多触发两次:第一次使用单个空格.然后,如果该方法返回 false
,则不会发生其他任何事情.但是,如果该方法返回 true
,则 shouldChangeCharactersIn
会在其末尾使用建议的字符串 + 空格触发更多.因此,如果您想使用键盘建议,您必须允许空格并(如果需要)稍后根据您的要求以某种方式删除它们.一种方法是像这样使用 defer
(未测试,但给你一个想法):
If user uses suggestion, shouldChangeCharactersIn
fires up to two times: first with single whitespace. Then if the method returns false
nothing else happens. But if the method returns true
then shouldChangeCharactersIn
fires ones more with suggested string + whitespace at the end of it. So if you want to use keyboard suggestions you have to allow whitespaces and (if needed) remove them later somehow depending on your demands. One way is using defer
like this (not tested, but to give you an idea):
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
}
这篇关于shouldChangeCharactersIn 结合建议文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!