使用PageController swift

时间:2019-06-23 13:58:04

标签: ios swift uipagecontrol

我有一个页面视图控制器,在其中显示一些项目,在主ViewController中,我希望能够通过使用按钮移至下一页。我已经将viewcontrollers添加到数组中,但是如何创建一个在下一个和后退按钮中调用的函数却使我感到困惑。

下面是我的代码

private var pageController: UIPageViewController!

    lazy var controllers: [UIViewController] = {
        let locVC = LocationVC()
        locVC.delegate = self
        let typeVC = TypeVC()
        typeVC.delegate = self
        return [locVC,
                typeVC]
    }() 

private func setupPageController() {

    self.pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    self.pageController.dataSource = self
    self.pageController.delegate = self
    pageController.view.translatesAutoresizingMaskIntoConstraints = false

    addChild(pageController)
    view.addSubview(pageController.view)
    NSLayoutConstraint.activate([
        pageController.view.topAnchor.constraint(equalTo: navView.bottomAnchor),
        pageController.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        pageController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        pageController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
    pageController?.setViewControllers([controllers[0]], direction: .forward, animated: false)

}

func viewControllerAtIndex(index: Int) -> UIViewController? {
        if controllers.count == 0 || index >= controllers.count {
            return nil
        }

        return UIViewController()
    }

    func backBtnClicked() {

        guard currentIndex - 1 >= 0 else { return }
        currentIndex -= 1
        guard let startingViewController = viewControllerAtIndex(index: currentIndex) else { return }
        pageController.setViewControllers([startingViewController], direction: .reverse, animated: false)
    }

所有viewcontrollers都有一个var pageIndex: Int = 0变量,我相信这将被用来检测当前页面

1 个答案:

答案 0 :(得分:0)

您需要(例如,转到分页器中的第一个vc)

pageController.setViewControllers([controllers[index]], direction: .forward, animated: true, completion: nil)