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

And*_*y A 5 cocoa-touch uikeyboard pushviewcontroller nsnotificationcenter ios

我用以下代码检测键盘何时显示.但是,当我使用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];
Run Code Online (Sandbox Code Playgroud)

rck*_*nes 15

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

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

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

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

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil];
}
Run Code Online (Sandbox Code Playgroud)

如果你想设置观察者然后将代码从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];
}
Run Code Online (Sandbox Code Playgroud)