Last active
December 30, 2015 06:48
-
-
Save bentford/7791449 to your computer and use it in GitHub Desktop.
Showing and hiding the keyboard on iOS
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)registerForKeyboardNotifications | |
{ | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(keyboardWillShow:) | |
name:UIKeyboardWillShowNotification object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(keyboardWillHide:) | |
name:UIKeyboardWillHideNotification object:nil]; | |
} | |
- (void)unregisterForKeyboardNotifications | |
{ | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
} | |
- (void)keyboardWillShow:(NSNotification *)notification { | |
NSTimeInterval animationDuration; | |
UIViewAnimationOptions curve; | |
[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration]; | |
[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve]; | |
// raw keyboard size, doesn't account for orientation | |
NSValue *aValue = [[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey]; | |
CGSize keyboardSize = [aValue CGRectValue].size; | |
// compute keyboard size for orientation | |
UIViewController *rootViewController = [AppDelegate delegate].viewController; | |
BOOL isPortrait = UIInterfaceOrientationIsPortrait(rootViewController.interfaceOrientation); | |
CGFloat keyboardHeight = isPortrait ? keyboardSize.height : keyboardSize.width; | |
CGFloat keyboardWidth = isPortrait ? keyboardSize.width : keyboardSize.height; | |
CGSize orientedKeyboardSize = CGSizeMake(keyboardWidth, keyboardHeight); | |
// run animation using keyboard's curve and duration | |
[UIView animateWithDuration:animationDuration delay:0.0 options:curve animations:^{ | |
// size or move views appropriately so they are not obscured by the keyboard | |
} completion:^(BOOL completion) { | |
}]; | |
} | |
- (void)keyboardWillHide:(NSNotification *)notification | |
{ | |
NSTimeInterval animationDuration; | |
UIViewAnimationOptions curve; | |
[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration]; | |
[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve]; | |
// hiding is a bit easier | |
// simply restore views back to original position | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment