Search code examples
iosswiftuiviewcontrolleruinavigationcontrollersegue

How to pass variable to a ViewController that is embedded in a Navigation Controller?


I want to pass data from ViewController1 to ViewController2. ViewController2 is embedded within a Navigation Controller (because I have a Segmented Control that corresponds to 3 Child View Controllers). My segue is directly from ViewController1 to the Navigation Controller.

enter image description here

I tried the following in ViewController1:

ViewController2().testID = "test value"

With the following in ViewController2:

var testID = ""

However testID does not update when I run print(testID) in ViewController2.

What is recommended for passing data from ViewController1 to ViewController2? Any help/advice is much appreciated!


Solution

  • You can pass the value by overriding the prepare(for segue:) function in ViewController1

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        // Get the new view controller using segue.destination 
        guard let destination = segue.destination as? UINavigationController else {
            return
        }
    
        guard let finalDestination = destination.viewControllers.first as? ViewController2 else {
            return
        }
    
        finalDestination.testID = "Test Value"
    }