IOS Swift: UIPageViewController – Turning page programmatically

iosswiftuipageviewcontrolleruiviewcontroller

I have a UIPageViewController, which works fine when we swipe left or right to turn pages.

class ViewController: UIViewController, UIPageViewControllerDataSource {
...
}

Now I intend to provide Previous/Next button on the page too, so that pages can be turned by clicking on these buttons.

How can I trigger the swipe left/right behaviour OR turn pages programmatically?


Note

This is a question for Swift language, not Objective-C.

Best Solution

There's generally no need to fiddle around with page indexes and what not. Chances are you are already implementing a dataSource: UIPageViewControllerDataSource, which has all of what you need to get a previous or next ViewController to display.

Swift 5 Example:

extension UIPageViewController {

    func goToNextPage() {
       guard let currentViewController = self.viewControllers?.first else { return }
       guard let nextViewController = dataSource?.pageViewController( self, viewControllerAfter: currentViewController ) else { return }
       setViewControllers([nextViewController], direction: .forward, animated: false, completion: nil)
    }

    func goToPreviousPage() {
       guard let currentViewController = self.viewControllers?.first else { return }
       guard let previousViewController = dataSource?.pageViewController( self, viewControllerBefore: currentViewController ) else { return }
       setViewControllers([previousViewController], direction: .reverse, animated: false, completion: nil)
    }

}

This way you're guaranteed that the pages you're transitioning to are exactly what the PageViewController's built in gestures would trigger.