Is there any way to detect when the Backspace/Delete key is pressed in the iPhone keyboard on a UITextField
that is empty? I want to know when Backspace is pressed only if the UITextField
is empty.
Based on the suggestion from @Alex Reynolds in a comment, I've added the following code while creating my text field:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleTextFieldChanged:)
name:UITextFieldTextDidChangeNotification
object:searchTextField];
This notification is received (handleTextFieldChanged
function is called), but still not when I press the Backspace key in an empty field. Any ideas?
There seems to be some confusion around this question. I want to receive a notification when the Backspace key is pressed. That's it. But the solution must also work when the UITextField
is already empty.
:) just for the title "Detect backspace", where I use
UIKeyboardTypeNumberPad
.I also meet the same question tonight, and following is my code to find it out:
Because with
UIKeyboardTypeNumberPad
, user can only input Number or backspace, so when the length of string is 0, it must be backspace key.Hope the above will do some help.
To Keep it Simple here is the only condition u need to check
In
UITextViewDelegate
:it works ok for me.
update for Chinese simplified pinyin and Chinese handwriting input:
base on the document says:
"If the user presses the
deleteKey
, the length of the range is 1 and an empty string object replaces that single character."Subclassing UITextField did not work for me on iOS 8.3, deleteBackward was never called.
Here is the solution I used, works on all iOS 8 versions and should work on other iOS versions as well
Something like this:
of course the hash is for one character string.
Swift implementation: