Skip to content

Instantly share code, notes, and snippets.

@obyknovenius
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save obyknovenius/5cc1299580fdce4f1b89 to your computer and use it in GitHub Desktop.

Select an option

Save obyknovenius/5cc1299580fdce4f1b89 to your computer and use it in GitHub Desktop.
Move view up when the keyboard appears.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShown:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShown:(NSNotification*)aNotification
{
NSDictionary* userInfo = [aNotification userInfo];
CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]];
[UIView setAnimationBeginsFromCurrentState:YES];
CGRect frame = self.view.frame;
frame.origin.y += CGRectGetHeight(keyboardFrame);
self.view.frame = frame;
[UIView commitAnimations];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
NSDictionary* userInfo = [aNotification userInfo];
CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]];
[UIView setAnimationBeginsFromCurrentState:YES];
CGRect frame = self.view.frame;
frame.origin.y -= CGRectGetHeight(keyboardFrame);
self.view.frame = frame;
[UIView commitAnimations];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment