简体   繁体   中英

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>

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];

PS To animate the content offset, use:

[scrollview setContentOffset:offsetSize animated:YES];

There is a contentInset property of UIScrollViews, you can set the contentInset to make additional space at the bottom to allow for scrolling without changing contentSize.

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, 100, 0.0);
scrollView.contentInset = contentInsets;

above code adds 100 points inset at the bottom.

By the way, there is an official document about this matter. It explains everything you should do. You can find it here . You can find what you are looking for under the section 'Moving Content That Is Located Under the Keyboard'

Try

  1. Create Scroll view
  2. Add View to the scroll view (In my case i added view as mainView).
  3. Set ScrollView autoresizing .
  4. Set MainView autoresizing .

  5. To set the Scroll content Size equal to the view created add below line

Add the below line

-(void)viewDidLayoutSubviews

{

[super viewDidLayoutSubviews];

self.scrollView.contentSize = self.mainView.frame.size;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM