0

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.

user773578
  • 1,161
  • 2
  • 13
  • 24

4 Answers4

0
[[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

lukaswelte
  • 2,951
  • 1
  • 23
  • 45
0

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!

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
0

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
  • when the field begins editing, prefix any string there with the space
  • when the user appends text as seen in shouldChangeCharactersInRange, append it.
  • if the user tries to delete the final last character, or a range that contains it, then return NO, make the change, then add back the leading space char.
  • when the textField is finished editing, remove the leading space
David H
  • 40,852
  • 12
  • 92
  • 138
0

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;
    }
Smit Shah
  • 209
  • 2
  • 9