richc
richc

Reputation: 1678

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

Upvotes: 1

Views: 564

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try it more early like

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

Upvotes: 3

Related Questions