Detect backspace in UITextField on a blank textfie

2019-01-26 21:26发布

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

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-26 22:06

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

查看更多
时光不老,我们不散
3楼-- · 2019-01-26 22:23

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.

查看更多
登录 后发表回答