UIPageViewController: get the currentPage

后端 未结 12 529
别那么骄傲
别那么骄傲 2021-02-03 22:22

I have been struggling with this issue for the last few days and after all this juggling I have figured out that all I need is the current Index from the datasource method to up

12条回答
  •  走了就别回头了
    2021-02-03 22:38

    My approach is quite simple:

    1. When the page (controller) is instantiated I pass in the page index, which at this point is known.

    2. Then in the delegate call below, iff the transition finished, I obtain the controller currently shown and cast it to my custom page class, before I fetch and update the currentPage with the associated page index.

    To keep things simple I setup the data source and delegate to be the WalkThroughController which embeds the page view controller.

    extension WalkThroughController: UIPageViewControllerDelegate {
    
        func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    
            guard finished, let currentPageController = pageViewController.viewControllers?.last as? WalkThroughPageViewController else {
                return
            }
    
            self.currentPage = currentPageController.pageIndex
        }
    
    }
    

    The take away point is to set the page index of the pages when they are created in the data source. With this approach it is very straight forward to retrieve it later.

提交回复
热议问题