UIPageController - 如果滑动取消,则检测当前页面(SWIFT 3. *)

时间:2016-11-08 11:38:17

标签: swift uipageviewcontroller

我目前有一个UIPageController,可以在滚动时正确检测上一页或下一页的索引

我需要解决的问题是......

实施例: - 用户向左或向右滚动但随后决定在滑动期间取消...因此保留在当前页面上。

pageIndex更改为待处理页面(下一页)而不是实际当前页面。

我的代码目前正在实现上述声明: -

func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {

    if let itemController = pendingViewControllers[0] as? PageContentViewController {

        nextIndex = itemController.pageIndex

        print("Page index = \(nextIndex)")
    }
}

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        currentIndex = nextIndex
        print("Current Page = \(currentIndex)")
    }


func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {



    let itemController = viewController as! PageContentViewController

    if itemController.pageIndex < numberOfPages {
        return getItemController(itemController.pageIndex+1)
    }

    return nil

}



func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

    let itemController = viewController as! PageContentViewController

    if itemController.pageIndex > 0 {

        return getItemController(itemController.pageIndex-1)
    }

    return nil
}

func getItemController(_ itemIndex: Int) -> PageContentViewController? {

    if itemIndex < numberOfPages {
        let pageItemController = self.storyboard!.instantiateViewController(withIdentifier: "Page1") as! PageContentViewController
        pageItemController.pageIndex = itemIndex

        return pageItemController
    }

    return nil
}

我希望在页面显示之前获取页码,以便显示特定对象等。

viewControllerAfter和viewControllerBefore似乎每次都没有被调用,因此我不能依赖这个委托方法

1 个答案:

答案 0 :(得分:2)

我不知道我是如何错过这个但是在didFinishAnimating方法中他们是一个完成块

因此以下代码解决了我的问题

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

    if completed
    {
        currentIndex = nextIndex

    }

    print("Current Page = \(currentIndex)")
}