Voici une mise en œuvre pour 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)
}
et est facilement invoqué en appelant :
self.scrollToPage(1, animated: true)
Editar:
Une façon plus agréable de procéder consiste à prendre en charge la pagination horizontale et verticale. Voici une extension pratique pour cela :
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)
}
}
Cela crée une extension sur UIScrollView où vous pouvez faire défiler n'importe quelle page, verticale ou horisontale.
self.scrollView.scrollTo(horizontalPage: 0)
self.scrollView.scrollTo(verticalPage: 2, animated: true)
self.scrollView.scrollTo(horizontalPage: 1, verticalPage: 2, animated: true)