【问题标题】:Is there a way to override the viewControllerBefore / After methods in UIPageViewControllerDataSource to avoid repeating code?有没有办法覆盖 UIPageViewControllerDataSource 中的 viewControllerBefore / After 方法以避免重复代码?
【发布时间】:2020-05-05 18:55:06
【问题描述】:

我在整个应用程序中创建了多个 PageViewController,它们都需要一些相同的配置,所以我想知道是否有办法覆盖这些方法或以更简洁的方式执行此操作。

现在,对于我创建的 4 个中的每一个,我都有以下设置代码。 唯一的变量是viewControllers数组(在PageViewController类中声明),否则这段代码要重复4次。

extension ThemeSelector: UIPageViewControllerDataSource {

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    guard let currentIndex = themes.firstIndex(of: viewController) else { return nil }

    // This is used to prevent the pageViewController from trying to instantiate a vc before that doesn't exist.
    if currentIndex > 0 { return themes[currentIndex - 1] }
    else { return nil }
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let currentIndex = themes.firstIndex(of: viewController) else { return nil }

    // This is used to prevent the pageViewController from trying to instantiate a vc after that doesn't exist.
    if currentIndex < themes.count - 1 { return themes[currentIndex + 1] }
    else { return nil}
}


// MARK: Pagination Dots
func presentationCount(for _: UIPageViewController) -> Int {
    return themes.count
}

func presentationIndex(for _: UIPageViewController) -> Int {
    guard let firstViewController = viewControllers?.first,
        let firstViewControllerIndex = themes.firstIndex(of: firstViewController) else {
            return 0
    }
    return firstViewControllerIndex
}

}

提前致谢。

【问题讨论】:

    标签: swift protocols extension-methods uipageviewcontroller


    【解决方案1】:

    您可以使用此设置代码创建 BasePageViewController 并继承。

    【讨论】:

    • 谢谢Hayk,这是一个很好的建议,解决了我的问题。
    • 我很乐意提供帮助。
    猜你喜欢
    • 2018-12-01
    • 2021-12-15
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2020-12-02
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多