Search code examples
iosswiftuipageviewcontroller

How to check when UIPageViewController VC changes to another?


I try to check when my UIPageViewController's VC changes to another by swiping. What function handles this, and how I can get the new page index?

I know about function:

func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
  //code
}

Thanks very much.


Solution

  • This little bit of code should do the trick:

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    
        guard completed else { return }
    
        guard let index = (pageViewController.viewControllers?.first as? ContentViewController)?.index else { return }
    
        guard let index = pageViewController.viewControllers?.first?.view.tag else { return }
    
        guard let vc = pageViewController.viewControllers?.first else { return }
    
        let index: Int
    
        switch vc {
        case is FirstViewController:
            index = 0
        case is SecondViewController:
            index = 1
        default:
            index = 2
        }
    }
    

    What you do here is manually saving the currently selected index. This should work as long as the transition is animated, which it should always be I guess.