jdog jdog - 1 year ago 138
Objective-C Question

UIScrollView not scrolling in iOS7 with autolayout on

I have a UIScrollView with a 6 textfields in it and a button inside of it. There is not enough content in the scrollView to make it scroll.

But when the keyboard shows, I would like the scrollview to scroll so the user doesn't have to dismiss the keyboard in order to select another textfield that is hidden by the keyboard.

I am using iOS7 and have autolayout enabled.

Any suggestions?

I am using storyboards and the only code I have is the following.

reg.h file

interface registerViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>

Answer Source

In order to make a scrollview scrollable, the content size must be larger than the scrollview's frame so the scrollview has something to scroll to. Use setContentSize to adjust the content size:

[scrollview setContentSize:CGSizeMake(width, height)];

In this case, you should adjust the size to view.frame.width, view.frame.height + keyboard_height, then adjust the content offset once the keyboard appears:

[scrollview setContentOffset:CGPointMake(0, 0 - keyboard_height)];

If for some screwy, autolayout-related reason this still doesn't make the view scrollable, implement this setContentSize function in viewDidLayoutSubviews in order to override the autolayout:

- (void)viewDidLayoutSubviews {
     [scrollview setContentSize:CGSizeMake(width, height)];

EDIT: To reset the scrollview after dismissing the keyboard, reset the scrollview content size to the scrollview's frame and the offset to zero:

[scrollview setContentSize:CGSizeMake(scrollview.frame.size.width, scrollview.frame.size.height)];
[scrollview setContentOffset:CGPointZero];

P.S. To animate the content offset, use:

[scrollview setContentOffset:offsetSize animated:YES];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download