Search code examples
iosswiftuicontainerview

Swift 4 How to pass data between ViewControllers and ContainerViews?


I have 3 ViewControllers: ViewController A and ViewController B, and Controller C which is actually a ContainerView consisting of two UIViews

My Storyboard

As you can see in the above picture, ViewController C has a clear background such that the "Test Label" can be seen in the UIViews of both ViewController A and B.

When I swipe up from ViewController A to go to ViewController B, I want to be able to perform some animation (fade in/out, translate, change text etc..). Let's say I want to change the text for from "Test Label" to "Some new text", the problem is as soon as I get into ViewController B, I get the "Unexpectedly found nil while unwrapping an Optional value" error.

Why am I getting nil and how can I change the label text properly?

This code seems to make sense but I can't get it right:

let containerViewController = ContainerViewController()
        containerViewController.testLabel.text = "Some new text"

I've also tried:

let containerViewController = storyboard?.instantiateViewController(withIdentifier: "containerViewController") as! containerViewController


        containerViewController.testLabel.text = "Some new text"

Do I have to add something in ViewController A's override func prepare?


Solution

  • You can give the embed segue from the container to the viewController C an identifier let say embedSegueFromBToC then catch the actual ViewController C in the prepare for segue in the parent controller let say B.

    So in B viewController add this:

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "embedSegueFromBToC" {
                if let viewControllerC =  segue.destination as? ViewControllerC {
                    viewContrllerC.loadViewIfNeeded() // you might need this since the need to access the testLabel which a UI component that need to be loaded
                    viewControllerC.testLabel.text = "Some new text"
                }
            }
        }