Autolayout Constraint - Keyboard Autolayout Constraint - Keyboard objective-c objective-c

Autolayout Constraint - Keyboard


Try it this way:

self.keyboardHeight.constant = -height;[self.view setNeedsUpdateConstraints];[UIView animateWithDuration:animationDuration animations:^{   [self.view layoutIfNeeded];}];

Remember this pattern because this should be the correct way to update constraint-based layouts (according to WWDC). You can also add or remove NSLayoutConstraints as long as you call setNeedsUpdateConstraints after.


If you're using UITableViewController, keyboard size should be automatically accommodated by iOS to adjust the contentInsets. But if your tableView is inside a UIViewController, you probably wanted to use this:

KeyboardLayoutConstraint in the Spring framework. Simplest solution I've found so far.KeyboardLayoutConstraint


Try the next code. In this case table view lays out at the bottom edge of the screen.

- (void)keyboardWillShow:(NSNotification *)notification { // UIKeyboardWillShowNotification    NSDictionary *info = [notification userInfo];    NSValue *keyboardFrameValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];    BOOL isPortrait = UIDeviceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation);    CGFloat keyboardHeight = isPortrait ? keyboardFrame.size.height : keyboardFrame.size.width;    // constrBottom is a constraint defining distance between bottom edge of tableView and bottom edge of its superview    constrBottom.constant = keyboardHeight;     // or constrBottom.constant = -keyboardHeight - in case if you create constrBottom in code (NSLayoutConstraint constraintWithItem:...:toItem:...) and set views in inverted order    [UIView animateWithDuration:animationDuration animations:^{        [tableView layoutIfNeeded];    }];}- (void)keyboardWillHide:(NSNotification *)notification { // UIKeyboardWillHideNotification    NSDictionary *info = [notification userInfo];    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];    constrBottom.constant = 0;    [UIView animateWithDuration:animationDuration animations:^{        [tableView layoutIfNeeded];    }];}