Use keyboard notifications to be alerted when the keyboard is presented e.g.:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
(Also remove these in viewWillDissapear:
[[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification]; [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
Then in the functions respectively:
- (void)keyboardWillShow:(NSNotification *) notification { CGRect appFrame = YOUR_VIEWS_FRAME CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; keyboardFrame = [self.view.window convertRect:keyboardFrame toView:self.view]; UITextField *current = THE_CURRENT_RESPONDER CGRect relativeFrame = [self.view convertRect:current.frame fromView:current.superview]; float difference = 0.0; //Here we give it a 20 pixel padding between the top of the keyboard and the bottom of the text field. if (CGRectIntersectsRect(relativeFrame, keyboardFrame)) difference = appFrame.size.height - keyboardFrame.size.height - 20 - relativeFrame.size.height - current.frame.origin.y; difference = difference < 0 ? difference : 0; NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; [UIView animateWithDuration:duration animations:^{ [self.scrolLView setContentOffset:CGPointMake(0, difference); } completion:^(BOOL finished) { }]; }
And:
- (void)keyboardWillHide:(NSNotification *) notification { NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; [UIView animateWithDuration:duration animations:^{ [self.scrolLView setContentOffset:CGPointZero]; } completion:^(BOOL finished) { }]; }