简体   繁体   中英

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

  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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM