5

我检测到键盘何时会显示以下代码。但是,当我使用 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];
4

1 回答 1

16

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

您可以在以下位置删除通知:

- (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)animated:

- (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];
}
于 2011-06-17T14:39:34.640 回答