UIPageViewController初始滑动调用两次

时间:2017-02-07 23:31:23

标签: ios swift

以下功能是当用户向右滑动时我显示不同视图的方式 self.viewControllerAtIndex()是我自己的返回视图的自定义函数。问题是第一次滑动输出“---------在0之前向右滑动”两次。然后完美地像预期的那样工作。

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    print("---------swipe Right before " + String(index))
    index += 1
    print("---------swipe Right " + String(index))

    if index == (products!.count) {
        index = 0
    }

    return self.viewControllerAtIndex(index:index)

}
=====CONSOLE OUTPUT=====
---------swipe Right before 0
---------swipe Right 1
---------swipe Right before 0
---------swipe Right 1

 func viewControllerAtIndex(index: Int) -> ViewController{

   return ViewController.init(id: index)
 }

出于某种原因,在第一次按照预期后的每次其他滑动。初始滑动是导致控制台输出的原因。这会导致我的视​​图序列如下所示(2个视图)

First Swipe
View1
Second Swipe
View1
Third Swipe
View2
Fourth Swipe
View1
Fifth Swipe
View2

我也是这样开始我的uiPageViewController

let array = [ViewController](repeating: ViewController.init(videos: (self.videos![self.products![self.index].id]!)), count: 1)

self.UIViewPageController?.setViewControllers(array, direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)

所以我在viewDidLoad上创建一个新的ViewController,然后当用户滑动时,我正在创建新的ViewControllers

2 个答案:

答案 0 :(得分:1)

我认为你应该避免在这种方法中进行索引状态管理。 Apple不保证调用此方法的情况。如果我不得不解释一下,我会说,虽然框架要求你提供应该提供的视图控制器,但你正在回答一个不同的问题:哪个视图控制器出现在你之前告诉我们的那个之后?

要解决这个问题,您需要使用原始的视图控制器数组,找到该数组中传入的视图控制器的索引,然后返回接下来的视图控制器(如果你在最后,则返回nil)数组)。

答案 1 :(得分:0)

评论太久了... 克里斯·特拉希(Chris Trahey)是正确的答案。

基于对viewControllerBefore / viewControllerAfter方法的误解,我的意思是“如果用户向右/向左滑动会发生什么”。就像您说的那样,这些方法只能回答以下问题:“哪个视图控制器在给定视图控制器之前/之后?”他们应该只回答这个问题,而没有任何副作用。

某些情况下的解决方案是将index属性添加到视图控制器类,并在创建时设置该索引。如果您不直接使用视图控制器数组,而是动态创建它们,那么这很有用。然后,您可以说assign而不是说array.index(of: vc)。 看到这里:https://stackoverflow.com/questions/25795093/swift-uipageviewcontroller-always-repeats-second-viewcontroller#=

编辑: 哦,如果您想对翻页做出实际反应,可以在vc.index中进行。