How to detect delete key on an UITextField in iOS 8?

后端 未结 10 1538
余生分开走
余生分开走 2020-11-30 00:56

I have subclassed UITextField and implemented the UIKeyInput protocol\'s deleteBackward method to detect backspace being pressed. This works fine on iOS 7 but not on iOS 8.<

10条回答
  •  野性不改
    2020-11-30 01:31

    This does not explicitly answer the original question but worth nothing that in the documentation for textField(_:shouldChangeCharactersIn:replacementString:), it says:

    "string: The replacement string for the specified range. During typing, this parameter normally contains only the single new character that was typed, but it may contain more characters if the user is pasting text. When the user deletes one or more characters, the replacement string is empty."

    Thus, we can detect backspaces in a UITextFieldDelegate if we implement textField(_:shouldChangeCharactersIn:replacementString:) and check if the length of string is 0.

    A lot of other answers here have used this same logic without referencing the documentation so hopefully getting it right from the source makes people more comfortable using it.

提交回复
热议问题