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

5.2k Views Asked by At

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.

3

There are 3 best solutions below

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

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
    }

}
0
On
- (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;
}