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.
To pass data back, the most common approach is to create a delegate property in your detail view controller, like this: class ViewControllerB: UIViewController { var selectedName: String = "Anonymous" weak var delegate: ViewControllerA! }
Step 1: Embed root view controller inside a navigation controller. In your storyboard, select the initial view controller in your hierarchy. With this view controller selected, choose the menu item Editor -> Embed In -> Navigation Controller .
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.
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With