Skip to content

Instantly share code, notes, and snippets.

@eralston
Created January 3, 2014 19:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eralston/8245097 to your computer and use it in GitHub Desktop.
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
///
/// 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