Swift 4 How to pass data between ViewControllers and ContainerViews?

三世轮回 提交于 2019-12-13 03:13:04

问题


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

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?


回答1:


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



回答2:


Correct, you have to use the prepare(for segue:..) override in your originating view controller, it will be passed the instance of ViewController B as the segue.destination.

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if let viewControllerB = segue.destination as? ViewControllerB
    {
        viewControllerB.testLabel.text = "Some new text"
    }
}

Check out this tutorial for more information: https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/



来源:https://stackoverflow.com/questions/56454153/swift-4-how-to-pass-data-between-viewcontrollers-and-containerviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!