Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shouldChangeCharactersIn Combined with Suggested Text

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?

like image 775
C6Silver Avatar asked Sep 01 '18 20:09

C6Silver


1 Answers

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
}
like image 65
4tuneTeller Avatar answered Nov 02 '22 13:11

4tuneTeller