问题
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