29

How do I navigate to a specific page programmatically. Basically I have an app with a scrollView populated with a bunch of subviews (tableViews in this case). When clicking on a subview it zooms in and the user can edit and navigate the table, however when I zoom back out I reload the entire view in case there were any changed made by the user. Of course reloading the view sends the user back to page 0. I've tried setting the pageControl.currentpage property but all that does is change the dot of the pageControl. Does that mean that something is wrong or do I need to do something else as well??

All that is controlling the page scrolling is this method:

- (void)scrollViewDidScroll:(UIScrollView *)sender 
{
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;

NSString *listName = [self.wishLists objectAtIndex:self.pageControl.currentPage];
self.labelListName.text = listName;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Glitch
  • 619
  • 2
  • 7
  • 16
  • 1
    possible duplicate of [Change page on UIScrollView](http://stackoverflow.com/questions/1926810/change-page-on-uiscrollview) – Max MacLeod Aug 14 '15 at 14:26

3 Answers3

54

You have to calculate the corresponding scroll position manually. To scroll to page i:

[scrollView setContentOffset:CGPointMake(scrollView.frame.size.width*i, 0.0f) animated:YES];
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • 1
    Since page width is equal to scroll view bounds width it's basically something like this: [scrollView setContentOffset:scrollView.bounds.size.width * i animated:YES]; – SteamTrout Nov 15 '10 at 14:04
  • Apparently you needed to supply a CGPoint for the offset value so creating a CGPoint and placing it as the offset worked like charm! Thanks a lot guys! – Glitch Nov 15 '10 at 14:20
  • You are right, Glitch. Sorry I missed the thing about `CGPoint`. Code corrected. – Ole Begemann Nov 15 '10 at 14:35
1

Swift 5 you can easily use scrollView.scrollRectToVisible

If the Horizontal paging scroll view implemented, which has the size of default view width of the device and wanted to navigate to number n page:

scrollView.scrollRectToVisible(CGRect(x: self.view.center.x * n, y: self.view.center.y, width: self.view.frame.width, height: self.view.frame.height) ,animated: true)

You just have to define the CGRect() position according to your scrollview configurations.

0

Swift 5 version of above answer by Ole Begemann

scrollView.setContentOffset( CGPoint(x: scrollView.frame.size.width * i, y: 0.0), animated: true)

Atul Vasudev A
  • 463
  • 3
  • 22