Skip to content

Instantly share code, notes, and snippets.

@parachvte
Created July 1, 2015 18:09
Show Gist options
  • Select an option

  • Save parachvte/848b55412a746e8efe53 to your computer and use it in GitHub Desktop.

Select an option

Save parachvte/848b55412a746e8efe53 to your computer and use it in GitHub Desktop.
iOS - Deal with keyboard
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Add observers for keyboard messages
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
[super viewWillDisappear:animated];
}
- (void)keyboardWillShow:(NSNotification *)notification {
// get keyboard size and loctaion
CGRect keyboardBounds;
[[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// Need to translate the bounds to account for rotation.
keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];
// set views with new info
// do something
// commit animations
[UIView commitAnimations];
[self ajustTableViewConstaints];
[self ajustTableViewOffset:@(NO)];
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:[duration doubleValue]];
[UIView setAnimationCurve:[curve intValue]];
// set views with new info
// do something
// commit animations
[UIView commitAnimations];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment