I am using autolayout with a scroll view. It is working great, but I need to be able to scroll to specific pages programmatically. Specifically, I need to scroll to the last page after the view loads. How do I do this? My scrolling essentially has the visual format shown below, except the number of pages is dynamic.
visual format for vertically scrolling (swap V and H for horizontally scrolling):
view hierarchy is scrollContainer(UIView) -> scrollView(UIScrollView) -> contentView(UIView) -> pages(UIView’s)
V:|scrollView|
H:|scrollView|
V:|contentView|
H:|contentView|
V:|[page1(==scrollContainer)][page2(==scrollContainer)][page3(==scrollContainer)]|
H:|[page1(==scrollContainer)]|
H:|[page2(==scrollContainer)]|
H:|[page3(==scrollContainer)]|
edit: clarifying my question
The code to offset the scrollview is below. But when can I get the origin of the page I want to scroll to using autolayout? If I put it in viewDidLayoutSubviews, it updates every time the device is rotated. I need to update just when the view is loaded. Is there a more appropriate method to override? Or is there a way of setting the origin with a constraint?
let lastPage = pages?.last
if lastPage != nil {
let origin = lastPage!.frame.origin
self.scrollView.setContentOffset(origin, animated: false)
}
If it's a horizontal scroll view:
If vertical:
Then just use the scroll view's method:
You can leave this code in
viewDidLayoutSubviews
, just add an if-statement to test if it's the first time or not: