Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll a UIScrollView on load when using auto layout

I have a UIScrollView that is set up in the viewDidLoad method of a UIViewController (I'll call it a ScrollViewController). The scroll view contains pages of horizontal content (similar to the native weather app).

When displaying the scrollview, it should be possible to choose which page it starts on. My pattern is this:

  • init a ScrollViewController. Nothing much happens in here. A currentPage property is defaulted to 0.
  • set the scrollViewController.currentPage to the desired page number.
  • in viewDidLoad of ScrollViewController, read self.currentPage and use scrollToRect or setContentOffset to scroll accordingly.

The scrolling implementation seems fine, since I am using the same code elsewhere to jump to certain pages. But on first load, nothing happens (that is, the scroll view is not scrolled to the desired page).

I think I have found the reason - it seems that the contentSize of the scroll view (which is derived by autolayout remember) is 0 during viewDidLoad, and this seems that this prevents scrolling. It is also zero during viewWillAppear. Only in viewDidAppear does the scroll work, which of course makes for an odd user experience.

How can I resolve this? Is it wise to somehow force a layout in viewDidLoad? Or some other approach?

like image 400
Ben Packard Avatar asked Aug 25 '13 14:08

Ben Packard


People also ask

How do I make my UI view scrollable?

You cannot make a UIView scrollable. That's what UIScrollView is for. However if you are using storyboards you can try to add constraints to the view so when you rotate the device the content remains inside the viewable area. Sounds like you already have some constraints setup so I would just play around with them.

How do you scroll on a storyboard?

You can scroll the scrollview in the Storyboard / Interface builder! Select the view inside scrollview in Document Outline, then scroll using your mouse or trackpad, you can see the view move.

How do I remove content layout guide?

Simply uncheck the Content Layout Guides. This option is found under the Size Inspector tab in storyboard. NOTE: This option is found under the Size Inspector tab in storyboard.


1 Answers

viewDidLayoutSubviews is what you are looking for. This is the method where all the subviews frames are completly initialized. So, try to call your scrollView's setup method inside it, in your viewController:

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self setupView];
}
like image 61
Lucas Eduardo Avatar answered Oct 23 '22 11:10

Lucas Eduardo