Detect backspace in UITextField on a blank textfield [duplicate]

拥有回忆 提交于 2019-11-28 05:24:15

问题


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.



来源:https://stackoverflow.com/questions/4351358/detect-backspace-in-uitextfield-on-a-blank-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!