如何将数据从视图控制器传递到导航控制器,然后传递到另一个视图控制器?

时间:2017-04-07 03:40:53

标签: ios swift xcode uiviewcontroller swift3

我有来自视图控制器的数据我想要传递另一个视图控制器,但是我将它设置为以模态方式呈现,所以我在它们之间有一个导航控制器。如何将数据从第一个视图控制器通过导航控制器传递到第二个视图控制器?

我在第一个视图控制器中有这个代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "presentPopup"
    {
        let destViewController = segue.destination as! NavigationViewController
        destViewController.myData2 = myData
    }
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}

然后导航控制器中的这段代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destViewController = segue.destination as! SecondViewController
    destViewController.myData3 = myData2
}

但它没有用。

2 个答案:

答案 0 :(得分:2)

您可以在First ViewController中使用它:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "presentPopup"
    {
        let destViewController = segue.destination as! NavigationViewController
        let secondViewcontroller = destViewController.viewcontrollers.first as! SecondViewcontroller
        secondViewcontroller.myData2 = myData
    }
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}

答案 1 :(得分:0)

如果storyBoard中有2个viewControllers,firstViewControllersecondViewController,则会在它们之间形成segue。

firstViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "presentPopup" {
        let destViewController = segue.destination as! secondViewController
        destViewController.myData2 = myData
    }     
}

secondViewController声明:

var myData2: [same type with myData]? // now you can use myData2

perfomeSegue()之后,myData2会有价值。