如何检测iPhone中按下的键盘键?

AtW*_*ork 12 iphone objective-c ios

我想在用户按任何键盘键时检测到.

任何只在键入任何字符时调用的方法,而不是在显示键盘时调用的方法.

谢谢!!

Nis*_*agi 40

每次用户按下键时,您都可以直接处理键盘事件:

如果是UITextField

- (BOOL)textField:(UITextField *)textField
          shouldChangeCharactersInRange:(NSRange)range
          replacementString:(NSString *)string {

    // Do something here...
}
Run Code Online (Sandbox Code Playgroud)

UITextView的情况下:

- (BOOL)textView:(UITextView *)textView
      shouldChangeTextInRange:(NSRange)range 
      replacementText:(NSString *)text {

    // Do something here...
}
Run Code Online (Sandbox Code Playgroud)

因此,每次使用键盘按下的每个键都会调用其中一个方法.

您也可以使用NSNotificationCenter.您只需要在ViewDidLoad方法中添加任何这些.

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
Run Code Online (Sandbox Code Playgroud)

UITextField:

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

然后你可以把你的代码放在方法中textFieldText::

- (void)textFieldText:(id)notification {

    // Do something here...
}
Run Code Online (Sandbox Code Playgroud)

的UITextView

[notificationCenter addObserver:self
                       selector:@selector(textViewText:)
                           name:UITextViewTextDidChangeNotification
                         object:yourtextView];
Run Code Online (Sandbox Code Playgroud)

然后你可以把你的代码放在方法中textViewText::

- (void)textViewText:(id)notification {

    // Do something here...
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 .

  • 注意:如果文本字段为空并且您按下删除键,则不会调用shouldChangeTextInRange :. 文本字段似乎检测到该字段没有改变,因此委托方法不需要被触发= / (5认同)