I have set up PageViewControll with 2 views. I am able to move between the views and the pageControl (Dots) correspond to the correct page- however tapping the dots doesn't scroll to the correct view just yet.
I found few answers on here on how to create the function but was not able to implement is successfully to make it work. The code for the page controller is below (without the tap function) The full code is :
func configurePageControl() {
pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 50,width: UIScreen.main.bounds.width,height: 50))
self.pageControl.numberOfPages = viewControllerList.count
self.pageControl.currentPage = 0
self.pageControl.alpha = 0.5
self.pageControl.tintColor = UIColor.white
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.white
self.view.addSubview(pageControl)
}
@IBAction func pageControltapped(_ sender: Any) {
guard let pageControl = sender as? UIPageControl else { return }
let selectedPage = pageControl.currentPage
self.setViewControllers([viewControllerList[selectedPage]], direction: .forward, animated: true, completion: nil)
}
}
thanks for any help!!
You need to create IBAction for pageControl
from which you can detect which dot was tapped.
Then, you need to use setViewControllers(_:direction:animated:completion:)
method to scroll page programmatically.
func setViewControllers(_ viewControllers: [UIViewController]?,
direction: UIPageViewController.NavigationDirection,
animated: Bool,
completion: ((Bool) -> Void)? = nil)
Here's the link to documentation
Use following code:
@IBAction func pageControltapped(_ sender: Any) {
guard let pageControl = sender as? UIPageControl else { return }
let selectedPage = pageControl.currentPage
self.setViewControllers([viewControllerList[selectedPage]], direction: .forward, animated: true, completion: nil)
}
Add target for pageControl to link it with IBAction:
func configurePageControl() {
//...your code as it is....
//add following line
self.pageControl.addTarget(self, action: #selector(pageControltapped(_:)), for: .touchUpInside)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With