使用 NSNotificationCenter 捕获按键事件

发布于 2024-10-03 21:51:59 字数 644 浏览 5 评论 0原文

这个解决方案 接收 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独难免 2024-10-10 21:51:59

每次按下按键时,通知只应出现一次。至少这是我在测试时得到的。我唯一能想到的是您调用了 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文