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.
Code like following:
At last, do forget to change the Custom Class property of the Text Field to "MyTextField"
Niklas Alvaeus's answer helped me out with a similar issue
I was limiting entry to a specific character set, but it was ignoring backspaces. So I had it check
range.length == 1
before trimming theNSString
. If it is true, I just return the string and don't trim it. See belowUpdate: See JacobCaraballo's answer for an example that overrides
-[UITextField deleteBackward]
.Check out
UITextInput
, specificallyUIKeyInput
has adeleteBackward
delegate method that always gets called when the delete key is pressed. If you're doing something simple, then you might consider just subclassingUILabel
and making it conform to theUIKeyInput
protocol, as done by SimpleTextInput and this iPhone UIKeyInput Example. Note:UITextInput
and its relatives (includingUIKeyInput
) are only available in iOS 3.2 and later.I have implemented the similar solution with minor improvements that will tell me that if the text field has any value while the user has tapped the backspace. This is useful for my case when I should only focus on another text field if the text field is empty when backspace pressed.
Swift 4:
Subclass
UITextField
:Implementation:
Objective-C:
Subclass
UITextField
:Now simply add MyTextFieldDelegate to your
UIViewController
and set yourUITextFields
myDelegate toself
: