Skip to content

Instantly share code, notes, and snippets.

@benvium
Created January 10, 2013 16:38
Show Gist options
  • Select an option

  • Save benvium/4503572 to your computer and use it in GitHub Desktop.

Select an option

Save benvium/4503572 to your computer and use it in GitHub Desktop.
When the keyboard appears, scroll the tableView up a pre-defined amount, so the content is nicely centered. I find this useful on a login page.
//-----------------------------------------------------
#pragma mark - When the keyboard appears, scroll the tableView up a pre-defined amount, so the content is nicely centered.
//-----------------------------------------------------
// http://stackoverflow.com/questions/1126726/how-to-make-a-uitextfield-move-up-when-keyboard-is-present
// Call this is viewDidLoad
- (void) setupKeyboard {
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:self.view.window];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:self.view.window];
_keyboardIsShown = NO;
}
// Call this in dealloc
- (void) cleanKeyboard {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardWillHide:(NSNotification *)n
{
[UIView animateWithDuration:.25 animations:^{
self.tableView.contentOffset = CGPointMake(0, 0);
}];
_keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)n
{
// This is an ivar I'm using to ensure that we do not do the frame size adjustment on the UIScrollView if the keyboard is already shown. This can happen if the user, after fixing editing a UITextField, scrolls the resized UIScrollView to another UITextField and attempts to edit the next UITextField. If we were to resize the UIScrollView again, it would be disastrous. NOTE: The keyboard notification will fire even when the keyboard is already shown.
if (_keyboardIsShown) {
return;
}
[UIView animateWithDuration:.25 animations:^{
self.tableView.contentOffset = CGPointMake(0, 70);
}];
_keyboardIsShown = YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment