OStack程序员社区-中国程序员成长平台

标题: ios - 检测 UIPageViewController 的当前页面 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:37
标题: ios - 检测 UIPageViewController 的当前页面

我想检测当前页面,以便在显示最后一页时修改按钮的标题,并在每次用户从最后一页滑回倒数第二页时重新修改。

现在这些是我的委托(delegate)方法和我的 ViewControllers 数组:

lazy var VCArr: [UIViewController] = {
    let firstVC = self.storyboard!.instantiateViewController(withIdentifier: "FirstTutorialPage")
    let secondVC = self.storyboard!.instantiateViewController(withIdentifier: "SecondTutorialPage")
    let thirdVC = self.storyboard!.instantiateViewController(withIdentifier: "ThirdTutorialPage")
    let fourthVC = self.storyboard!.instantiateViewController(withIdentifier: "FourthTutorialPage")
    return [firstVC, secondVC, thirdVC, fourthVC]
}()

委托(delegate)方法

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

    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return nil
    }

    guard self.VCArr.count > previousIndex else {
        return nil
    }

    return self.VCArr[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard nextIndex < self.VCArr.count else {
        return nil
    }

    guard self.VCArr.count > nextIndex else {
        return nil
    }

    return self.VCArr[nextIndex]
}

有人可以帮我准确检测显示的最后一页吗?我尝试了一些方法,但每个人都向我展示了错误的索引。这些方法在显示倒数第二页时检测到最后一个索引。

谢谢大家。



Best Answer-推荐答案


我的解决方案在于实现 UIPageViewControllerDelegate 的功能 pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted 并执行以下操作:

if completed {
    if let currentViewController = pageViewController.viewControllers?.first,
    let index = pages.index(of: currentViewController) {
        currentIndex = index
    }
}

其中 pages 是我的页面 View Controller 的一个属性,我在其中存储要呈现的所有 View Controller ,而 currentIndex 是一个用于跟踪索引的属性当前页面(又名 View Controller ),以便在我的代码的其他部分中使用它。

关于ios - 检测 UIPageViewController 的当前页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45553670/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4