简体   繁体   中英

How to pass data from parent view controller to child container view controller

I am trying to send data from ParentVC to a childVC using a container. The container is not embedded as it is used multiple times in my app, so I cannot use prepareForSegue. I am instantiating the containerVC in ViewDidLoad. How do I pass data to the containerVC on load? I have seen answers on SO to passing from Child to Parent, but not this way round. Thanks in advance for any help.

import UIKit

class ParentVC: UIViewController {

    @IBOutlet var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let childVC = storyboard!.instantiateViewController(withIdentifier: "ChildVC") as! ChildVC
        addChild(childVC)
        childVC.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        childVC.view.frame = containerView.bounds
        containerView.addSubview(childVC.view)
        childVC.didMove(toParent: self)

        // pass values to child
        childVC.boolVariable = true // THIS DOESN'T WORK. HOW TO PASS DATA TO THE CHILD?
    }
 }

You can try it more early like

let childVC = storyboard!.instantiateViewController(withIdentifier: "ChildVC") as! ChildVC
childVC.boolVariable = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM