Last active
April 5, 2016 21:45
-
-
Save brcosm/5545292 to your computer and use it in GitHub Desktop.
How to deal with keyboard resizing in a UIViewController
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
- (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; | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from iOS8 onwards, orientation check is no longer necessary. if you view was presented form sheet, how would your calculation be?