5

I have data from a view controller I want to pass another view controller, but I have it set to present modally, so I have a navigation controller between them. How do I pass data from the first view controller through the navigation controller to the second view controller?

I have this code in the first view controller:

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

Then this code in the navigation controller:

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

But it doesn't work.

Ethan Zhao
  • 229
  • 1
  • 6
  • 18

2 Answers2

5

You can use this in 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.
}
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39
0

If you have 2 viewControllers, firstViewController and secondViewController in storyBoard, you make segue between them.

In firstViewController:

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

In secondViewController declare:

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

After perfomeSegue(), the myData2 will have value.

Bista
  • 7,869
  • 3
  • 27
  • 55
Ronald Vo
  • 64
  • 3
  • 1
    I tried this, and it didn't work, since the segue is connected to the navigation view controller between the two view controllers. – Ethan Zhao Apr 07 '17 at 04:32