问题
I have a UITextField
and am using the delegate method func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
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.
How can we use shouldChangeCharactersIn
to check text entry but still allow for the use of suggested text?
回答1:
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
}
来源:https://stackoverflow.com/questions/52131894/shouldchangecharactersin-combined-with-suggested-text