pageViewController viewControllerAfter / Before dataSource方法被调用两次

时间:2018-10-31 11:11:58

标签: ios swift uipageviewcontroller

我想以类似寻呼机的方式显示一些数据,所以我想使用UIPageViewController,这基本上就是我所做的:

struct ModelTest {
    var number: Int
}


class PagerViewController: UIPageViewController, UIPageViewControllerDataSource {

    var currentIndex = 0

    var models: [ModelTest] = [
        ModelTest(number: 1),
        ModelTest(number: 2),
        ModelTest(number: 3),
        ModelTest(number: 4),
        ModelTest(number: 5)
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dataSource = self
        if let firstModel = models.first {
            setViewControllers([ModelViewController(firstModel)], direction: .forward, animated: true, completion: nil)
        }
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let nextIndex = currentIndex + 1
        guard nextIndex < models.count else {
            return nil
        }
        self.currentIndex += 1
        return ModelViewController(models[nextIndex])
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        let previousIndex = currentIndex - 1
        guard previousIndex >= 0 else {
            return nil
        }
        self.currentIndex -= 1
        return ModelViewController(models[previousIndex])
    }

}

但是,由于某种原因,dataSource方法viewControllerAfterviewControllerBefore有时会被调用两次。您是否知道为什么以及如何解决这个问题?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

当您将'UIPageViewController'而不是'UIViewController'子类化时,无需再次设置委托。

删除下面的行,它应该可以正常工作。

  

self.dataSource =自我