Created
January 3, 2014 19:41
-
-
Save eralston/8245097 to your computer and use it in GitHub Desktop.
An example in Objective-C of animating the UI based on keyboard appearance/disappearance
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
/// | |
/// Category to help with animating UIView instances | |
/// | |
@implementation UIView (Animation) | |
-(void)translateX:(float)x andY:(float)y | |
{ | |
CGPoint center = self.center; | |
center.x += x; | |
center.y += y; | |
self.center = center; | |
} | |
-(void)completeTranslateX:(float)x andY:(float)y | |
{ | |
self.transform = CGAffineTransformMakeTranslation(2*x, 2*y); | |
} | |
-(void)resetTransform | |
{ | |
self.transform = CGAffineTransformIdentity; | |
} | |
@end | |
/// | |
/// Example UIViewController subclass implementation | |
/// | |
@implementation ExampleViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view from its nib. | |
// Register for keyboard show events | |
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; | |
[nc addObserver:self | |
selector:@selector(keyboardWillShow:) | |
name:UIKeyboardWillShowNotification | |
object:nil]; | |
[nc addObserver:self | |
selector:@selector(keyboardWillHide:) | |
name:UIKeyboardWillHideNotification | |
object:nil]; | |
} | |
#pragma mark - Keyboard show/hide animation Implementation | |
- (void)keyboardWillShow:(NSNotification *)notification | |
{ | |
// Use notification parameter for duration to support localized keyboards (EG, Japanese) | |
NSDictionary *info = [notification userInfo]; | |
NSNumber *number = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey]; | |
double duration = [number doubleValue]; | |
int distance = -10; | |
[UIView animateWithDuration:duration | |
delay:0.0 | |
options:UIViewAnimationOptionCurveEaseInOut | |
animations:^{ | |
[_exampleView translateX:0 andY:distance]; | |
} | |
completion:^(BOOL finished){ | |
[_exampleView completeTranslateX:0 andY:distance]; | |
}]; | |
} | |
-(void)keyboardWillHide:(NSNotification *)notification | |
{ | |
NSDictionary *info = [notification userInfo]; | |
NSNumber *number = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey]; | |
double duration = [number doubleValue]; | |
int distance = 10; | |
[UIView animateWithDuration:duration | |
delay:0.0 | |
options:UIViewAnimationOptionCurveEaseInOut | |
animations:^{ | |
// Top | |
[_exampleView translateX:0 andY:distance]; | |
} | |
completion:^(BOOL finished){ | |
// Reset their positions to prevent weird bug with UIAlerts | |
[_exampleView resetTransform]; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment