3

Possible Duplicate:
Detect backspace in UITextField

I am trying to detect the backspace key envent on my UITextfield which is empty. I saw this but could not figure it out. Any elaborate answer or code snippet would be helpful

Detect backspace in UITextField

Community
  • 1
  • 1
jacob
  • 31
  • 1
  • 5
  • Can you explain a little more about what you are trying to accomplish by doing this? – Ryan Dec 04 '10 at 02:24

2 Answers2

3

I've found it not to be possible.

When the UITextField is empty, the following delegate method isn't called.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

I conquered this by constantly having a space in the field, and when I detect a backspace and the field only contains a space, I return NO in the delegate method.

if ([string isEqualToString:@""] && [textField.text isEqualToString:@" "]){
    // Backspace called on 'empty' field.
    return NO;
}

Visually, this is as good as the field being empty, and it's a workaround to the delegate method not being called on an empty field.

Hope that helps.

Tom Irving
  • 10,041
  • 6
  • 47
  • 63
  • "I conquered this by constantly having a space in the field" - how you achieved that? Could you provide some sample code? What if user wrote in the textfield letter "a", then press backspace twice? When you inject space char to the field? Thanks! – Piotr Sep 23 '11 at 20:46
  • I don't let the user use the delete key if there's only a space in the field - see the example code above. – Tom Irving Sep 23 '11 at 22:36
  • There must be a better way to do this. – Adam Waite Jan 21 '13 at 18:09
  • 1
    You could also try a zero-width character like \u200B – Tom Irving Jan 21 '13 at 18:31
0

:) just for the title "Detect backspace", where I use UIKeyboardTypeNumberPad.

I also meet the same question tonight, and following is my code to find it out:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog([NSString stringWithFormat:@"%d", [string length]]);
}

Because with UIKeyboardTypeNumberPad, user can only input Number or backspace, so when the length of string is 0, it must be backspace key.

Hope the above will do some help.

iGatiTech
  • 2,306
  • 1
  • 21
  • 45
Jason Lee
  • 3,200
  • 1
  • 34
  • 71