How to make a UIScrollView auto scroll when a UITextField becomes a first responder

I hope this example will help you You can scroll to any point by this code.

scrollView.contentOffset = CGPointMake(0,0);

So if you have textfield, it must have some x,y position on view, so you can use

CGPoint point = textfield.frame.origin ;
scrollView.contentOffset = point 

This should do the trick,

But if you don't know when to call this code, so you should learn UITextFieldDelegate methods

Implement this method in your code

- (void)textFieldDidBeginEditing:(UITextField *)textField {
// Place Scroll Code here
}

I hope you know how to use delegate methods.


I know this question has already been answered, but I thought I would share the code combination that I used from @Adeel and @Basil answer, as it seems to work perfectly for me on iOS 9.

-(void)textFieldDidBeginEditing:(UITextField *)textField {

    // Scroll to the text field so that it is
    // not hidden by the keyboard during editing.
    [scroll setContentOffset:CGPointMake(0, (textField.superview.frame.origin.y + (textField.frame.origin.y))) animated:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField {

    // Remove any content offset from the scroll
    // view otherwise the scroll view will look odd.
    [scroll setContentOffset:CGPointMake(0, 0) animated:YES];
}

I also used the animated method, it makes for a much smoother transition.


There is nothing you have to do manually. It is the default behavior. There are two possibilities as to why you are not seeing the behavior

  1. The most likely reason is that the keyboard is covering your UITextField. See below for solution
  2. The other possibility is that you have another UIScrollView somewhere in the view hierarchy between the UITextField and the UIScrollView that you want to auto scroll. This is less likely but can still cause problems.

For #1, you want to implement something similar to Apple's recommendations for Moving Content That Is Located Under the Keyboard. Note that the code provided by Apple does not account for rotation. For improvements on their code, check out this blog post's implementation of the keyboardDidShow method that properly translates the keyboard's frame using the window.