Is there a way to get notifications of when the user presses the backspace key on a UITextField, even if the field is empty?
I would like to be able to trigger some code when the user backspaces on an empty field.
Is there a way to get notifications of when the user presses the backspace key on a UITextField, even if the field is empty?
I would like to be able to trigger some code when the user backspaces on an empty field.
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
This is how you get notified on every key the user presses. Then you have to figure out (i think in the notification is a property for it) which key was pressed.
Or you can use the textfield delegate function
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
To figure out what key was pressed
Since you need to detect not when text was deleted but when the backspace key is pressed, you need to do quite a bit more than implement UITextFieldDelegate
.
Read this blog post about how UITextField
forwards all the UIKeyInput
methods to a private class UIFieldEditor
. The writer dynamically subclasses UIFieldEditor
at runtime in order to detect these events.
Hope this points you in the right direction!
I can think of a technique to get you what you want but its going to take a bit of code. In essence, always keep a single Unicode "space" character at the front of the string. I don't have my book with me, but there is a really thin space character you can use.
You will put most of your code here:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
This will detect backspace. Now you can do whatever when backspace is pressed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField==txtMobileNo)
{
const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
int isBackSpace = strcmp(_char, "\b");
if (isBackSpace == -8) {
NSLog(@"isBackSpace");
if (textField.text.length == 9)
{
}
return YES; // is backspace
}
else if (textField.text.length == 10) {
return YES;
}
}
return NO;
}