太快滑动或快速连续向左和向右滑动时,如何跟踪pageViewController的索引

时间:2019-06-29 13:43:53

标签: ios swift uipageviewcontroller

我的View Controller旁边有一个Page View Controller,它是无限循环滚动pageViewController。

通常,我可以为页面ViewController中的每个视图控制器使用属性indexController跟踪当前视图控制器(代码中的ContentViewController)的索引。

class ContentViewController: UIViewController {

    var indexController = 0

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

并且我通过具有2个属性nextIndexcurrentIndex的2个函数跟踪索引

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
        }

    }

但是当我如此快速地向左滚动或非常快地连续左右滑动时,上面的2个函数无法正确调用,并且currentIndex无法正确更新。

我该怎么办?我可以防止滑动得太快吗?请有人帮我解决这个问题!

1 个答案:

答案 0 :(得分:0)

尝试将pageviewcontroller的uiscrollview的委托设置为您的视图控制器。

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

然后在此函数中获取pageViewController的当前视图控制器

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {}

然后正确更新索引