Get user swiping direction in UIPageViewController

后端 未结 5 2054
长发绾君心
长发绾君心 2020-12-06 11:20

These two methods viewControllerBeforeViewController and viewControllerAfterViewController of the UIPageViewControllerDataSource don\'

5条回答
  •  再見小時候
    2020-12-06 11:31

    You should use both the willTransitionToViewControllers: and the didFinishAnimating: delegate methods to work out whether the transition is forward or backward. Declare a couple of index variables at the start of your class, say currentIndex and nextIndex (both Int).

    In the willTransitionToViewControllers method, set the nextIndex equal to the itemIndex of the pending view controller:

    EDIT

    func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) {
        // the page view controller is about to transition to a new page, so take note
        // of the index of the page it will display.  (We can't update our currentIndex
        // yet, because the transition might not be completed - we will check in didFinishAnimating:)
        if let itemController = pendingViewControllers[0] as? PageItemController {
            nextIndex = itemController.itemIndex
        }
    }
    

    END EDIT

    You can work out at this point whether the transition will be forward or backward: if nextIndex > currentIndex, then forward; if nextIndex < currentIndex then backward. Then in didFinishAnimating, if completed is true (so it completed the transition to the next view controller), set currentIndex equal to nextIndex so you can use currentIndex wherever you need to indicate which page is currently on screen:

    EDIT

    func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
        if (completed) {
            // the page view controller has successfully transitioned to the next view
            // controller, so we can update our currentIndex to the value we obtained 
            // in the willTransitionToViewControllers method:
            currentIndex = nextIndex
    
        }
    }
    

    Note that the first argument to these methods is the pageViewController (instance of UIPageViewController), not pageItemController which you have in your current code.

    Finally, just to note: that enum you refer to (UIPageViewControllerNavigationDirection) is used only in the setViewControllers(_, direction:) method.

    END EDIT

提交回复
热议问题