Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a UIScrollView from automatically scrolling when a UITextField is touched out of the scrollview's frame?

By default, if a textfield is a child of a scrollview and is touched when it is partially outside of the frame of the parent scrollview, the scrollview scrolls up a little. For example, let's say we have a scroll view with a frame height of 200, but a contentSize height of 260 and we put a text field at position 220. Now I scroll up and position the textfield half inside of the scrollview's frame and let the other half get cut off. If I touch this textfield, I notice that the scrollview automatically scrolls up by a couple pixels before the keyboard comes up. This is problematic because I already have my own scrolling code, so when this happens, it ends up scrolling twice as far as I want it to. Is there any way to remove this default behavior?

like image 932
Scott Pfeil Avatar asked Aug 24 '11 19:08

Scott Pfeil


2 Answers

It sounds like your scrollview is getting moved in response to the keyboard showing instead of the text field being tapped. Take a look at Apple's Managing the Keyboard documentation; it has a helpful section on scrollviews.

like image 173
Ash Furrow Avatar answered Nov 13 '22 09:11

Ash Furrow


A similar question already has been answered here: https://stackoverflow.com/a/5673026/550177

You can also try to reset the scrollview's contentOffset when the textfield becomes first responder. Implemement the text field delegate like this:

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.scrollView setContentOffset:_scrollView.contentOffset animated:NO];
}

This code removes that automatic animation when the textfield is selected. I've tested with iOS 6.1 in the simulator.

like image 41
Felix Avatar answered Nov 13 '22 10:11

Felix