How to scroll view up when keyboard appears? How to scroll view up when keyboard appears? xcode xcode

How to scroll view up when keyboard appears?


I have made solutions that work with scroll and non-scroll views using keyboard notification and a detection of the current first responder, but sometimes I use this trivial solution instead: The simple way is to detect the opening keyboard via the text field delegate's textViewDidBeginEditing: method and to move the entire view up. The easiest way to do this is with something along the lines of changing self.view.bounds.origin.y to -100 (or whatever). Use the corresponding textViewShouldEndEditing: method to set it to the opposite, which is 100 in this case. Changing bounds is a relative procedure. After changing it the frame is moved but the bounds origin is still zero.


Since I found it, I use TPKeyboardAvoiding - https://github.com/michaeltyson/TPKeyboardAvoiding.

It is working great, and is very easy to setup:

  • Add a UIScrollView into your view controller's xib
  • Set the scroll view's class to TPKeyboardAvoidingScrollView (still in the xib, via the identity inspector)
  • Place all your controls within that scroll view

You can also create it programmatically, if you want.


There is a class for the same need inside a UITableViewController ; it is only needed in case you support a version of iOS below 4.3.


@BenLu and other users who are facing problem of the function are never getting called is because of following reason:As the delegate inbuild function bydefaults return void instead of BOOL this is how it should be as follows:

 -(void)textFieldDidBeginEditing:(UITextField *)textField{    [UIView beginAnimations:nil context:NULL];    [UIView setAnimationDuration:0.35f];    CGRect frame = self.view.frame;    frame.origin.y = -100;    [self.view setFrame:frame];    [UIView commitAnimations];}-(void)textFieldDidEndEditing:(UITextField *)textField{    [UIView beginAnimations:nil context:NULL];    [UIView setAnimationDuration:0.35f];    CGRect frame = self.view.frame;    frame.origin.y = 100;    [self.view setFrame:frame];    [UIView commitAnimations];}