Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from view controller to a navigation controller and then to another view controller?

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.

like image 746
Ethan Zhao Avatar asked Apr 07 '17 03:04

Ethan Zhao


People also ask

How do you pass a string value from one viewController to another view controller?

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

How do I add a view controller to my navigation controller?

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 .


1 Answers

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.
}
like image 166
Sour LeangChhean Avatar answered Oct 19 '22 17:10

Sour LeangChhean