OK. So looking at my old code, I remembered, I do not use 2 observers (UIKeyboardDidShowNotification
/UIKeyboardDidHideNotification
). I use a single observer (UIKeyboardWillChangeFrameNotification
), that is fired of each event: Keyboard hiding, keyboard showing, keyboard changing frame.
In my case, the text box and send button are in nested in a UIView
and this is view is added in the view
of the UIViewController
, above everything else.
I add the observer in viewDidAppear
and remove the observer in viewWillDisappear
.(to avoid any notification firing when view is not active).
The above information is not necessary for your case, just added it for information sake. Relevant code is as follows:
ADD OBSERVER:
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
HANDLE NOTIFICATION:
- (void) keyboardWillChangeFrame:(NSNotification*)notification {
NSDictionary* notificationInfo = [notification userInfo];
CGRect keyboardFrame = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
[UIView animateWithDuration:[[notificationInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]
delay:0
options:[[notificationInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue]
animations:^{
CGRect frame = self.textViewContainer.frame;
frame.origin.y = keyboardFrame.origin.y - frame.size.height;
self.textViewContainer.frame = frame;
} completion:nil];
}
You might have to make a few adjustments to the frame.origin.y...
line for correct calculations. I don't know whether you have a UITabBarController
or any bars at the bottom. The safest bet here would be:
frame.origin.y = self.view.frame.size.height - keyboardFrame.size.height - X;
Where X
is 0 if your VC covers the whole screen. If not, use the heights of any bottom bars.