【发布时间】: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