shouldChangeCharactersIn Combined with Suggested Text

喜欢而已 提交于 2021-02-08 01:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!