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.
In .h file add UIKeyInput delegate
improved Formatting
Using the TextField Delegate method:
Add the following code in above method to detect delete event
Try the
delegate
Then check if the
range.length == 1
which seems to be the case whenbackspace
is hit.Rather than trying to preconstruct what WILL BE in the text field or figure out what special character has been entered in the
shouldChangeCharactersInRange
method, I would suggest doing the following:This allows you to call a method directly after the current operation completes. What's cool about this is that, by the time it completes, the modified value will already be in the
UITextField
. At that point, you can just check its length and/or validate based on what's there.Yup, use below method to detect backspace, when textField is empty.
Need to add UITextFieldDelegate
yourTextField.delegate = self (MUST REQUIRED)
Swift:
Objective C: