是否可以知道用户是在键入还是删除文本字段中的字符?

ser*_*487 9 iphone xcode objective-c uitextfielddelegate

我正在使用文本字段委托方法"shouldChangeCharactersInRange",我想知道是否有任何方法可以判断用户是否正在删除字符或键入字符?谁知道?谢谢.

Mar*_*ams 27

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


Ish*_*shu 5

逻辑: 要查找删除,您需要在每个字母类型之后构建一个字符串然后您可以检查每个更改字符串是否为buid字符串的子字符串然后它表示用户删除最后一个字母,如果构建字符串是textField文本的子字符串然后用户添加一封信.

您可以使用与此逻辑一起使用的委托方法,也可以使用通知

您可以使用此通知来查找任何类型的更改

添加这些行 viewDidLoad

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter addObserver:self
                           selector:@selector (handle_TextFieldTextChanged:)
                               name:UITextFieldTextDidChangeNotification
                             object:yourTextField];
Run Code Online (Sandbox Code Playgroud)

并使这个功能

- (void) handle_TextFieldTextChanged:(id)notification {

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

}
Run Code Online (Sandbox Code Playgroud)