【问题标题】:Capture key press event using NSNotificationCenter使用 NSNotificationCenter 捕获按键事件
【发布时间】:2011-05-14 08:38:27
【问题描述】:

这个解决方案 Receive iPhone keyboard events

提供了一种使用通知中心捕获按键事件的方法。

[[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 次。

这是正常的还是我做错了什么?

【问题讨论】:

    标签: iphone keyboard keypress nsnotificationcenter


    【解决方案1】:

    每按一次键,通知应该只出现一次。至少这是我在测试时得到的。我唯一能想到的就是你给addObserver:selector:name:object:打了三遍电话。

    也许你在几个视图控制器中都在做这件事而忘记调用removeObserver:name:object:

    或者你在一个被多次调用的函数中调用addObserver:selector:name:object:viewDidLoad 通常是放置这样代码的好地方。

    【讨论】:

    • 我是 viewDidLoad 函数中的 addObserver,但控制器为 3 个不同的实例初始化了 3 次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多