I'm working on my embedded table views. They should scroll up when the keyboard hides some textfields. But I have several view controllers in my navigation view controller with this behaviour. So far my code registration and unregistration code is:
- (void)viewDidLoad
{
[super viewDidLoad];
[self registerForKeyboardNotifications];
}
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
But if I'm showing the keyboard in let's say view controller number 3 in my navigation controller, the keyboardWasShown method is called three times. Doesn't this matter or do I need to unregister everytime the viewWillDisappear?
You should move [self registerForKeyboardNotifications];
to viewDidAppear
and unregister in viewDidDisappear
.
By registering in viewDidLoad
and unregistering in dealloc
, especially within a navigation controller, the notification will fire once for every view controller on the navigation stack. You only need to call it for the currently visible view.
Alternatively, you could subclass the navigation controller and have it call a method on its currently visible controller. Then you don't have to do all this registering and unregistering. Just register once in a nav controller subclass and have that class pass the message along to the proper view controller.