Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIKeyboardWillShowNotification wrongly called from next class in stack

I detect when the keyboard will show with the below code. However, when I push to another screen using pushViewController and open the keyboard in that screen, keyboardWillShow is getting called! Is this really correct?

[[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];
like image 354
Andy A Avatar asked Jun 17 '11 14:06

Andy A


1 Answers

Yes, this is correct behavior. Since the view that pushes the other view is still alive and the notifications are app wide.

You could remove the notification in the:

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

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

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

And if you want to set the observer then place you code from viewDidLoad to 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];
}
like image 144
rckoenes Avatar answered Oct 21 '22 13:10

rckoenes