Change page on UIScrollView
Here is an implementation for Swift 4:
func scrollToPage(page: Int, animated: Bool) {
var frame: CGRect = self.scrollView.frame
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0
self.scrollView.scrollRectToVisible(frame, animated: animated)
}
and is easily invoked by calling:
self.scrollToPage(1, animated: true)
Edit:
A nicer way of doing this is to support both horizontal and vertical pagination. Here is a convenient extension for that:
extension UIScrollView {
func scrollTo(horizontalPage: Int? = 0, verticalPage: Int? = 0, animated: Bool? = true) {
var frame: CGRect = self.frame
frame.origin.x = frame.size.width * CGFloat(horizontalPage ?? 0)
frame.origin.y = frame.size.width * CGFloat(verticalPage ?? 0)
self.scrollRectToVisible(frame, animated: animated ?? true)
}
}
This creates an extension on UIScrollView where you can scroll to any page, vertical or horisontal.
self.scrollView.scrollTo(horizontalPage: 0)
self.scrollView.scrollTo(verticalPage: 2, animated: true)
self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)
You just tell the buttons to scroll to the page's location:
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageNumberYouWantToGoTo;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];