在页面视图控制器中导航控制器

时间:2015-07-06 04:28:02

标签: ios swift uinavigationcontroller navigation uipageviewcontroller

我尝试将一系列UINavigationControllers添加到单个UIPageViewController,就像在页面之间添加滑动导航一样。我使用标准视图控制器取得了一些成功,但我现在尝试添加导航控制器。这是我的故事板:

enter image description here

我想要做的是在第3行的所有页面之间实例化滑动导航(如Snapchat)。由于它们都通向其他视图控制器,因此每个视图控制器都嵌入在其自己的导航控制器中。这是我的代码:

class ViewController: UIViewController, UIPageViewControllerDataSource { // <-- Error here

// Sets up UIPageViewController. Must add to array count and instantiate new VCs.
    var myNavControllers = Array(count: 3, repeatedValue:UINavigationController())

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        let pvc = segue.destinationViewController as! UIPageViewController

        pvc.dataSource = self // <-- Error here

        let storyboard = UIStoryboard(name: "Main", bundle: nil);

        var vc0 = storyboard.instantiateViewControllerWithIdentifier("Nav1") as! UINavigationController
        var vc1 = storyboard.instantiateViewControllerWithIdentifier("Nav2") as! UINavigationController
        var vc2 = storyboard.instantiateViewControllerWithIdentifier("Nav3") as! UINavigationController
        var vc3 = storyboard.instantiateViewControllerWithIdentifier("Nav4") as! UINavigationController


        self.myNavControllers = [vc0, vc1, vc2, vc3]

        pvc.setViewControllers([myNavControllers[1]], direction:.Forward, animated:true, completion:nil)

    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UINavigationController) -> UINavigationController? {
        var currentIndex =  find(self.myNavControllers, viewController)!+1
        if currentIndex >= self.myNavControllers.count {
            return nil
        }
        return self.myNavControllers[currentIndex]
    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UINavigationController) -> UINavigationController? {
        var currentIndex =  find(self.myNavControllers, viewController)!-1
        if currentIndex < 0 {
            return nil
        }
        return self.myNavControllers[currentIndex]
    }

}

问题是,我有两个错误。一个class: ViewController声明:Type 'ViewController' does not conform to protocol 'UIPageViewControllerDataSource'。另一个位于pvc.dataSource = self,错误为:Cannot assign a value of type 'ViewController' to a value of type 'UIPageViewControllerDataSource?'

我能做的事情能完成吗?如果是这样,我是否需要在某处更改我的代码或以完全不同的方式实现这一点?

1 个答案:

答案 0 :(得分:0)

您定义的协议位于ViewController,但应在UIPageViewController类中定义。

class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
}

为此,您需要创建一个新的类,该类应该与您在故事板上的页面视图控制器相关联。