Last active
August 29, 2015 13:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]; | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
keyboardWillShow:
andkeyboardWillHide:
could be refactored into a common method.