is it possible to know if user is typing or deleting characters in a textfield?

青春壹個敷衍的年華 提交于 2019-12-10 12:46:36

问题


I am using the text field delegate method "shouldChangeCharactersInRange" and I wanted to know if there is any way to tell if user is deleting characters or typing characters? Anyone know? thanks.


回答1:


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.length > 0)
    {
         // We're deleting
    }
    else
    {
        // We're adding
    }
}



回答2:


Logic: For finding deletion you need to build a string after each letter type then you can check on each change if the string is sub string of the buid string then it means user delete last letter and if build string is sub string of textField text then user add a letter.

you can use delegate method which you are using with this logic or you can use notification

you can use this notification for finding any kind of change

add these lines in viewDidLoad

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter addObserver:self
                           selector:@selector (handle_TextFieldTextChanged:)
                               name:UITextFieldTextDidChangeNotification
                             object:yourTextField];

and make this function

- (void) handle_TextFieldTextChanged:(id)notification {

  //you can implement logic here.
    if([yourTextField.text isEqulatToString:@""])
    {   
        //your code
    }

}



回答3:


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    if (newLength > [textField.text length])
      // Characters added
    else
      // Characters deleted
    return YES;
}


来源:https://stackoverflow.com/questions/5190097/is-it-possible-to-know-if-user-is-typing-or-deleting-characters-in-a-textfield

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