UIPageViewController添加为子视图时无法识别滑动

时间:2018-07-24 13:18:58

标签: swift uipageviewcontroller

此外,委托或dataSource方法都没有被调用。

从拥有该视图的viewController的viewDidLoad中调用

setupPageView,该视图嵌入了pageViewContoller。

我在这里俯瞰着什么吗?

func setupPageView() {
    pageView = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [.interPageSpacing : 9])
    pageView.dataSource = self
    pageView.delegate = self
    pageView.setViewControllers([graphViews[0]], direction: .forward, animated: true, completion: nil)

    self.addChild(pageView)
    let bounds = pageViewContainer.bounds
    pageView.view.frame = bounds
    pageViewContainer.addSubview(pageView.view)
    pageView.didMove(toParent: self)
}

使用以下代码手动更改页面效果很好:

@IBAction func segmentedControlChanged(_ sender: UISegmentedControl) {
    var direction: UIPageViewController.NavigationDirection = .forward
    let newIndex = sender.selectedSegmentIndex
    if newIndex == index {
        return
    }
    if newIndex < index {
        direction = .reverse
    }
    index = newIndex
    pageView.setViewControllers([graphViews[index]], direction: direction, animated: true, completion: nil)
}

扩展名GraphPageView:UIPageViewControllerDelegate {

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

    if completed {
        //update index
        guard let currentVC = pageViewController.viewControllers?[0] else { fatalError("No Current VC")}
        guard let currentIndex = graphViews.index(of: currentVC) else { fatalError("No VC found") }
        self.index = currentIndex
    }
}

}

扩展名GraphPageView:UIPageViewControllerDataSource {

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    //
    if index == 0 { //@ begining of stack
        return nil
    } else {
        return graphViews[index - 1]
    }
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    //
    if index == graphViews.count { //@ end of stack
        return nil
    } else {
        return graphViews[index + 1]
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试通过以下行进行交互

pageView.isUserInteractionEnabled = true

当一个视图封装在其他视图中但需要捕获触摸时,这会有所帮助

答案 1 :(得分:0)

您应该更改viewControllerBeforeviewControllerAfter内的索引以反映当前索引,因此在滚动时分别获取下一个/上一个索引,请查看此pager