Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tap on pageControl to scroll to another view (tap on the dots)

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!!

like image 715
roypnyc Avatar asked Mar 28 '19 19:03

roypnyc


1 Answers

  1. You need to create IBAction for pageControl from which you can detect which dot was tapped.

  2. 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)
}
like image 124
Bhaumik Avatar answered Sep 25 '22 18:09

Bhaumik