点击pageControl滚动到另一个视图(点按一下)

时间:2019-03-28 19:44:37

标签: ios swift swift4 uipageviewcontroller

我已经用2个视图设置了PageViewControll。 我能够在视图之间移动,而pageControl(点)对应于正确的页面-但是点击这些点还不能滚动到正确的视图。

我在这里没有找到关于如何创建函数的答案,但是无法成功实现。 下面是页面控制器的代码(不带点击功能) 完整的代码是:

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


    }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

  1. 您需要为pageControl创建IBAction,可以从中检测出点击了哪个点。

  2. 然后,您需要使用setViewControllers(_:direction:animated:completion:)方法以编程方式滚动页面。

    func setViewControllers(_ viewControllers: [UIViewController]?, 
          direction: UIPageViewController.NavigationDirection, 
           animated: Bool, 
         completion: ((Bool) -> Void)? = nil)
    

    Here's the link to documentation

使用以下代码:

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

为pageControl添加目标以将其与IBAction链接:

func configurePageControl() {
    //...your code as it is....
    //add following line
    self.pageControl.addTarget(self, action: #selector(pageControltapped(_:)), for: .touchUpInside)
}