我已经在一个应用中创建了多个PageViewControllers,它们都需要一些相同的配置,所以我想知道是否有一种方法可以覆盖这些方法或以一种更简洁的方式进行操作。
现在,对于我创建的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
}
}
谢谢。
答案 0 :(得分:2)
您可以使用此设置代码创建BasePageViewController并继承。