使用 NSNotificationCenter 捕获按键事件
这个解决方案 接收 iPhone 键盘事件
提供了一种使用通知中心捕获按键事件的方法。
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
........
-(void) keyPressed: (NSNotification*) notification
{
NSLog([[notification object]text]);
}
它工作正常,但是对于从键盘上按下的每个键, keyPressed 函数都会被调用 3 次。
这是正常现象还是我做错了什么?
特奥
this solution
Receive iPhone keyboard events
offers a way to capture the keypress event using notification center.
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
........
-(void) keyPressed: (NSNotification*) notification
{
NSLog([[notification object]text]);
}
It works ok, but for every key that is been pressed from the keyboard the keyPressed function gets called 3 times.
Is this normal or am i doing something wrong?
Teo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次按下按键时,通知只应出现一次。至少这是我在测试时得到的。我唯一能想到的是您调用了
addObserver:selector:name:object:
三次。也许您在多个视图控制器中执行此操作,但忘记调用
removeObserver:name:object:
?或者您在一个被多次调用的函数中调用
addObserver:selector:name:object:
?viewDidLoad
通常是放置此类代码的好地方。The notification should only appear once per key pressed. At least that is what I get when testing. The only thing I can think of is that you are calling
addObserver:selector:name:object:
three times.Perhaps you are doing it in several view controllers and forget to call
removeObserver:name:object:
?Or you are calling
addObserver:selector:name:object:
in a function that gets called several times?viewDidLoad
is normally a good place to put code like this.