UIKeyboardWillShowNotification错误地从堆栈中的下一个类调用

时间:2011-06-17 14:35:03

标签: ios cocoa-touch nsnotificationcenter uikeyboard pushviewcontroller

我通过以下代码检测键盘何时显示。但是,当我使用pushViewController推送到另一个屏幕并在该屏幕中打开键盘时,keyboardWillShow正在调用!这真的是对的吗?

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardWillShow:) 
                                             name:UIKeyboardWillShowNotification 
                                           object:nil];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardWillHide:) 
                                             name:UIKeyboardWillHideNotification 
                                           object:nil];

1 个答案:

答案 0 :(得分:15)

是的,这是正确的行为。 由于推送其他视图的视图仍然存在且通知是应用程序范围。

您可以删除以下内容中的通知:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil];
}

如果你想设置观察者,那么将你的代码从viewDidLoad放到viewWillAppear:(BOOL)动画:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardWillShow:) 
                                             name:UIKeyboardWillShowNotification 
                                           object:nil];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardWillHide:) 
                                             name:UIKeyboardWillHideNotification 
                                           object:nil];
}