MarkosDarkin MarkosDarkin - 1 year ago 212
iOS Question

Reliable way to track Page Index in a UIPageViewController - Swift

I have a UIPageViewController (custom one) inside a Container located in a regular UIViewController. i need to be able to call an event with each Page Change but ONLY if it really did change and not only half way or anything of that sort.


func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?

is unreliable and not called each time for some reason.

if your answer contains anything about willTransitionToViewControllers or didFinishAnimating please elaborate and not just mention them, since i already know they exist but dont understand the proper way to use them.

Thank you

Answer Source

Use didFinishAnimating it has a completed and finished property so you know the page has actually changed. From the pageViewController you can get the currently displayed page, then get the position of this VC in your model.

First make sure your ViewController adopts UIPageViewControllerDelegate

Set the delegate (e.g. in viewDidLoad)

pageViewController.delegate = self

The implement the following function:

    func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if (completed && finished) {
            if let currentVC = pageViewController.viewControllers?.last {
                let index = myViewControllers.indexOf(currentVC)
                //do something with index