Change page on UIScrollView
I have a UIScrollView with 10 pages. I am able to flick between them. I also want to have 2 buttons (a back button and a next button) which when touched will go to the previous or next page. I can't seem to figure out a way to do this though. A lot of my code comes from Apple's page control sample code. Can anybody help?
Thanks
Solution 1:
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];
Solution 2:
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)
Solution 3:
scroll.contentOffset = CGPointMake(scroll.frame.size.width*pageNo, 0);
Solution 4:
scrollRectToVisible was not working for me, so I had to animate the contentOffset. This code works in swift 3.
func scrollToPage(_ page: Int) {
UIView.animate(withDuration: 0.3) {
self.scrollView.contentOffset.x = self.scrollView.frame.width * CGFloat(page)
}
}