I've created several PageViewControllers throughout an app and they all require some of the same configuration, so I was wondering if there's a way to override the methods or do this in a cleaner way.
Right now, for every one of the 4 I created, I have the following setup code. The only variable is the array of viewControllers (which is declared in the PageViewController class), otherwise this code has to be repeated 4 times.
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
}
}
Thanks in advance.
You can create BasePageViewController with this setup code and inherit.