iOS Swift: UIPageViewController - Turning page programmatically

后端 未结 6 824
我寻月下人不归
我寻月下人不归 2020-12-13 19:35

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

class ViewController: UIViewController, UIPageViewControllerDataSou         


        
6条回答
  •  情歌与酒
    2020-12-13 19:56

    The Swift 3 version of SuitedSloth's answer (with a small tweak to the animated parameter as I needed it to be animated by default, but still taking a parameter in the function) in case anyone needs it:

    extension UIPageViewController {
    
        func goToNextPage(animated: Bool = true) {
            guard let currentViewController = self.viewControllers?.first else { return }
            guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
            setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
        }
    
        func goToPreviousPage(animated: Bool = true) {
            guard let currentViewController = self.viewControllers?.first else { return }
            guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
            setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
        }
    
    }
    

提交回复
热议问题