programmatically scroll to a specific page/position with autolayout iOS

895 Views Asked by At

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)
    }
2

There are 2 best solutions below

3
On BEST ANSWER

If it's a horizontal scroll view:

CGPoint lastPage = CGPointMake((numberOfPages - 1) * pageWidth, 0.0f);

If vertical:

CGPoint lastPage = CGPointMake(0.0f, (numberOfPages - 1) * pageHeight);

Then just use the scroll view's method:

 [scrollView setContentOffset:lastPage animated:YES];

You can leave this code in viewDidLayoutSubviews, just add an if-statement to test if it's the first time or not:

if (!self.alreadyScrolled) {
    [self scrollToDesiredPage];
    self.alreadyScrolled = YES;
}
0
On

You should use:

CGPoint desiredOffset = CGPointMake(0.0,desiredPageNumber * pageHeight);
[self.scrollView setContentOffset:desiredOffset animated:YES];

Obviously tweak it as you need to. I don't believe you can or should achieve this by animating constraints, because of the unique way autolayout treats scroll views.