I assume you present the keyboard by calling becomeFirstResponder
on some UI component.
If the keyboard appears after your view is presented, you should check where that call is performed. Calling it in viewDidLoad
or similarly early should cause the keyboard to be shown as the view animates in.
Your layout should also handle the keyboard changes properly. The keyboard size can change even after it's presented. For example the emoji/quick type keyboards are taller than the default keyboard.
You should perform your constraint changes in a combination of UIKeyboard[Will/Did]ShowNotification
, UIKeyboard[Will/Did]HideNotification
and UIKeyboardWillChangeFrameNotification
. In your case, UIKeyboardWillShowNotification
should do the trick.
The userInfo
dictionary contains a lot of information about the keyboard. You find the final frame of the keyboard in UIKeyboardFrameEndUserInfoKey
. If you animate the changes in your layout, you can use values in UIKeyboardAnimationCurveUserInfoKey
and UIKeyboardAnimationDurationUserInfoKey
to animate with the same animation as the keyboard.
- (void)viewDidLoad {
[super viewDidLoad];
// Don't forget to remove the observer when appropriate.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[self.textField becomeFirstResponder];
}
- (void)keyboardWillShow:(NSNotification *)notification {
CGFloat keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
[self.viewHeightConstraint setConstant:keyboardHeight];
// You can also animate the constraint change.
}
Such setup will also work if the keyboard is presented from the get-go.