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.
The best use that I have found for detecting backspace is detecting when the user has pressed backspace in an empty
UITextField
. For example, if you have 'bubbled' recipients in the mail app, when you hit backspace in theUITextField
, it selects the last 'bubbled' recipient.This can be done in a similar way to Jacob Caraballo's answer. But in Jacob's answer, if the
UITextField
has one character left when you hit backspace, by the time the delegate message is received, theUITextField
will already be empty, so you're effectively detectingbackspace
on a text field with at most one characters.Actually, if you want to detect
backspace
on aUITextField
with exactly zero characters (empty), then you should send the message to thedelegate
before the call tosuper deleteBackward
. For example:The interface for such a text field would look something like this:
I've founded other way easier than
subclass
solution. Even its little bit strange but it works ok.It's a little bit strange for result of compare is -8. Maybe I'll wrong in some point of
C Programming
. But its right work ;)For the ones who has problems about the Jacob's answer I implemented my textfield subclass as following and it works great!
In iOS 6, the deleteBackward method is called on the UITextField when backspace is pressed, including when the field is empty. So you can subclass UITextField and provide your own deleteBackward implementation (invoking super's as well.)
I'm still supporting iOS 5 though so I'll need a combination of Andrew's answer and this.
This may be a long shot but it could work. Try setting the text field's text to a zero width space character
\u200B
. When backspace is pressed on a text field that appears empty, it will actually delete your space. Then you can just reinsert the space.May not work if the user manages to move the caret to the left of the space.
please use below code it will help you to detect keyboard delete key even if you textfield is empty.
Objective C :
- (BOOL)keyboardInputShouldDelete:(UITextField *)textField { return YES; }
Swift :