ios 如何检测在iphone中按下的键盘键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16016729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect Keyboard key pressed in iphone?
提问by AtWork
I want to detect whenever the user presses any keyboard key.
我想检测用户何时按下任何键盘键。
Any method which is called only on typing any character and not when keyboard is shown.
任何仅在键入任何字符时调用而不在显示键盘时调用的方法。
Thanks!!
谢谢!!
回答by Nishant Tyagi
You can directly handle keyboard events every-time a user presses a key :
每次用户按下一个键时,您都可以直接处理键盘事件:
In case of UITextField
在UITextField 的情况下
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Do something here...
}
In Case of UITextView:
在UITextView 的情况下:
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
// Do something here...
}
So every-time one of these method is called for each key you press using keyboard.
因此,每次使用键盘按下的每个键都会调用这些方法之一。
You can use NSNotificationCenter also. You only need do add any of these in ViewDidLoad method.
您也可以使用 NSNotificationCenter。您只需要在 ViewDidLoad 方法中添加任何这些。
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
UITextField :
UITextField :
[notificationCenter addObserver:self
selector:@selector(textFieldText:)
name:UITextFieldTextDidChangeNotification
object:yourtextfield];
Then you can put your code in method textFieldText:
:
然后你可以把你的代码放在方法中textFieldText:
:
- (void)textFieldText:(id)notification {
// Do something here...
}
UITextView
用户界面文本视图
[notificationCenter addObserver:self
selector:@selector(textViewText:)
name:UITextViewTextDidChangeNotification
object:yourtextView];
Then you can put your code in method textViewText:
:
然后你可以把你的代码放在方法中textViewText:
:
- (void)textViewText:(id)notification {
// Do something here...
}
Hope it helps .
希望能帮助到你 。
回答by Oscar Gomez
Assuming the keyboard is showing as a result of the user tapping on a UITextfield, you can make yourself the delegate and implement this method:
假设键盘显示为用户点击 UITextfield 的结果,您可以让自己成为委托并实现此方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
It will be called every time a user presses a key.
每次用户按下一个键时都会调用它。