Skip to content

Instantly share code, notes, and snippets.

@brcosm
Last active April 5, 2016 21:45
Show Gist options
  • Save brcosm/5545292 to your computer and use it in GitHub Desktop.
Save brcosm/5545292 to your computer and use it in GitHub Desktop.
How to deal with keyboard resizing in a UIViewController
- (void)observeKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)stopObservingKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardWillShow:(NSNotification *)n
{
CGRect frame = self.view.frame;
CGRect keyboardFrame = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIDeviceOrientation o = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsLandscape(o)) {
frame.size.width -= keyboardFrame.size.width;
} else {
frame.size.height -= keyboardFrame.size.height;
}
[UIView animateWithDuration:[n.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.frame = frame;
}];
}
- (void)keyboardWillHide:(NSNotification *)n
{
CGRect frame = self.view.frame;
CGRect keyboardFrame = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIDeviceOrientation o = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsLandscape(o)) {
frame.size.width += keyboardFrame.size.width;
} else {
frame.size.height += keyboardFrame.size.height;
}
[UIView animateWithDuration:[n.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.frame = frame;
}];
}
@acegreen
Copy link

acegreen commented Apr 5, 2016

from iOS8 onwards, orientation check is no longer necessary. if you view was presented form sheet, how would your calculation be?

if (UIDeviceOrientationIsLandscape(o)) {
        frame.size.width += keyboardFrame.size.width;
} else {
        frame.size.height += keyboardFrame.size.height;
}

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