I have a UIPageViewController with a PageControl programmatically built in. I have an array that keeps track of the view controllers that can be paged through, and I am trying to get the PageControl to show the dot that correlates to the current view controller page.
I have the following code for paging through backwards and forwards:
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let vcIndex = viewControllerList.index(of: viewController) else {
return nil
}
let previousIndex = vcIndex - 1
guard previousIndex >= 0 else {return nil}
guard viewControllerList.count > previousIndex else {return nil}
self.pageControl.currentPage = previousIndex
return viewControllerList[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let vcIndex = viewControllerList.index(of: viewController) else {return nil}
let nextIndex = vcIndex + 1
guard viewControllerList.count != nextIndex else {return nil}
guard viewControllerList.count > nextIndex else {return nil}
self.pageControl.currentPage = nextIndex
return viewControllerList[nextIndex]
}
When I set the current page of the PageControl to either nextIndex or previousIndex, I believe it should show the correct dot for the page of the current view controller being shown, however it often misses the middle index (there are three dots total). It usually just goes back and forth between the 1st and 3rd dots, and is not accurate.
If there's a better way to do this I will accept other answers as ways as well.
it's because you set pageControl's current index in the wrong place. You have to set it in:
func pageViewController(UIPageViewController, willTransitionTo: [UIViewController])
Called before a gesture-driven transition begins.
or
func pageViewController(UIPageViewController, didFinishAnimating: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool)
Called after a gesture-driven transition completes.
both methods are from UIPageViewControllerDelegate