Reputation: 26476
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?
Upvotes: 5
Views: 1426
Reputation: 12369
You should be able to set content size manually. Where do you insert the pages inside the scroll view? I would suggest inserting them inside viewDidLoad
or viewWillAppear
and then scrolling to the desired page just after inserting them by setting its contentOffset
.
Upvotes: 0
Reputation: 11675
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];
}
Upvotes: 8