iOS Swift: UIPageViewController - Turning page programmatically

后端 未结 6 832
我寻月下人不归
我寻月下人不归 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:50

    Here is the swift 4 implementation with the delegates as well.

    Since I also use the UIPageViewControllerDelegate, and the delegate methods weren't called with most of the setViewController solutions.

    Thanks to Andrew Duncan's for his comment about the delegate.

    // Functions for clicking next and previous in the navbar, Updated for swift 4
    @objc func toNextArticle(){
        guard let currentViewController = self.viewControllers?.first else { return }
    
        guard let nextViewController = dataSource?.pageViewController( self, viewControllerAfter: currentViewController ) else { return }
    
        // Has to be set like this, since else the delgates for the buttons won't work
        setViewControllers([nextViewController], direction: .forward, animated: true, completion: { completed in self.delegate?.pageViewController?(self, didFinishAnimating: true, previousViewControllers: [], transitionCompleted: completed) })
    }
    
    @objc func toPreviousArticle(){
        guard let currentViewController = self.viewControllers?.first else { return }
    
        guard let previousViewController = dataSource?.pageViewController( self, viewControllerBefore: currentViewController ) else { return }
    
        // Has to be set like this, since else the delgates for the buttons won't work
        setViewControllers([previousViewController], direction: .reverse, animated: true, completion:{ completed in self.delegate?.pageViewController?(self, didFinishAnimating: true, previousViewControllers: [], transitionCompleted: completed) })
    }
    

提交回复
热议问题