Detect backspace in UITextField on a blank textfie

2019-01-26 21:52发布

问题:

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

回答1:

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.



回答2:

:) 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.