Search code examples
iosswiftuipageviewcontroller

How to tracking index of pageViewController when swipe too fast or swipe to left and right continuously very fast


I have a Page View Controller in side my View Controller, which is infinite loop scroll pageViewController.

normaly, I can tracking index of current View Controller (ContentViewController in my code) with property indexController for each view controller in pageViewController.

class ContentViewController: UIViewController {

    var indexController = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

and i tracking index via 2 function with 2 property nextIndex and currentIndex

func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        if let vc = pendingViewControllers[0] as? ContentViewController {
            nextIndex = vc.indexController
        }
    }

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        let prevIndex = currentIndex
        if completed {
            currentIndex = nextIndex
        }
        else {
            nextIndex = currentIndex
        }

    }

but when i scroll to left so fast or swipe left and right continuously very fast, 2 function above does not call correctly, and currentIndex not update correctly.

what can i do? Can i prevent swipe too fast? somebody help me to solve this problem, please!


Solution

  • try set delegate of uiscrollview of pageviewcontroller to your view controller.

    for view in pageViewController!.view.subviews {
                if let scrollView = view as? UIScrollView {
                    scrollView.delegate = self
                }
            }
    

    then get current view controller of pageViewController in this func

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {}
    

    then update your index correctly