我正在使用UIPageViewController
在两个ViewController之间滑动。我试图显示有效的指示器点(请参阅addDots
)。但是不知何故,点只会在下一次滑动时发生变化,而在我滑动至上一个视图时不会发生变化。
有人可以告诉我我哪里做错了吗?
这是我的代码:
import UIKit
class LeasingTutorialViewController: UIPageViewController, UIPageViewControllerDataSource {
var pageControl = UIPageControl()
lazy var viewControllerList:[UIViewController] = {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc1 = sb.instantiateViewController(withIdentifier: "leasingPageOne")
let vc2 = sb.instantiateViewController(withIdentifier: "leasingPageTwo")
return [vc1, vc2]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
addDots()
if let firstViewController = viewControllerList.first as? LeasingPageOneViewController {
self.setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil)
}
}
func addDots() {
let color = UIColor(red: 24/255, green: 90/255, blue: 189/255, alpha: 1)
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 100,width: UIScreen.main.bounds.width,height: 50))
pageControl.numberOfPages = viewControllerList.count
pageControl.currentPage = 0
pageControl.tintColor = color
pageControl.pageIndicatorTintColor = UIColor.lightGray
pageControl.currentPageIndicatorTintColor = color
self.view.addSubview(pageControl)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let vcIndex = viewControllerList.firstIndex(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.firstIndex(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]
}
}