Skip to content

Instantly share code, notes, and snippets.

@brockboland
Last active August 29, 2015 13:57
Show Gist options
  • Save brockboland/9863500 to your computer and use it in GitHub Desktop.
Save brockboland/9863500 to your computer and use it in GitHub Desktop.
iOS 7: Resize the bottom constraint on a view when the keyboard displays. Don't copy-paste directly: the property needs to go in the interface, and be connected to the constraint from IB.
// Based on http://stackoverflow.com/a/12925659/2185
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
- (void)viewDidLoad {
[super viewDidLoad];
// Subscribe to the keyboard will show notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
// Get the height of keyboard + inputAccessoryView, if there is one
CGFloat keyboardHeight = CGRectGetHeight([kbFrame CGRectValue]);
// Adjust the size of the constraint
self.bottomConstraint.constant += keyboardHeight;
[self.view setNeedsUpdateConstraints];
NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:animationDuration animations:^{
[self.view layoutIfNeeded];
}];
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyboardHeight = CGRectGetHeight([kbFrame CGRectValue]);
// Adjust the size of the constraint
self.bottomConstraint.constant -= keyboardHeight;
[self.view setNeedsUpdateConstraints];
NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:animationDuration animations:^{
[self.view layoutIfNeeded];
}];
}
@brockboland
Copy link
Author

keyboardWillShow: and keyboardWillHide: could be refactored into a common method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment