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:
ScrollViewController
. Nothing much happens in here. A currentPage
property is defaulted to 0.scrollViewController.currentPage
to the desired page number.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?
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.
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.
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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With