How to detect UIKeyboard "backspace" button touch on UITextField?

24,900

Solution 1

if the UITextField is empty, the shouldChangeTextInRange delegate method is not called You can subclass UITextField and override this method:

-(void)deleteBackward;
{
    [super deleteBackward];
    NSLog(@"BackSpace Detected");
}

since UITextField is compliant to the UITextInput protocol, this method is implemented, and you can override it to detect when backspace is pressed. Then, you can write your own protocol/delegate method to alert your custom textfield delegate if the backspace is detected.

Solution 2

First of all your UIViewController that references the UITextField needs to conform to the UITextFieldDelegate protocol. Then set your class as delegate to the UITextField (eg. [myTextField setDelegate:self] ). Then in your class you add the following. When a string of "" is sent as the replacementString you know it's backspace.

(BOOL)textField:(UITextField *)textField 
      shouldChangeCharactersInRange:(NSRange)range 
      replacementString:(NSString *)string
{                
    if ([string isEqualToString:@""]) {
        NSLog(@"Backspace");            
    }
    return YES;
}

Solution 3

Temporary i'm inserting a zero space char on textFieldDidBeginEditing

textField.text = @"\u200B";

on backspace, it remove that chars, but graphically it's the same!

It's an hack, it works, but it hide placeholder text... not good...

Share:
24,900
elp
Author by

elp

code lover. linkedin || twitter || blog

Updated on May 01, 2020

Comments

  • elp
    elp about 4 years

    How can i detect backspace button pressed on UIKeyboard?

    enter image description here

    thanks


    EDIT: Is there any keyboard delegate that returns key pressed value?

  • Natan R.
    Natan R. about 11 years
    In my opinion, this should be the accepted answer!!!
  • ide
    ide over 10 years
    +1 This answer is much simpler than the ones at stackoverflow.com/questions/1977934/….
  • Andrew Bennett
    Andrew Bennett over 9 years
    This doesn't work on iOS8 - there's an Apple bug. Hopefully it'll be fixed in iOS8.1
  • vrunoa
    vrunoa over 9 years
    Still not working on IOS8.1, have you found another solution @AndrewBennett ?