如何将数据从父视图控制器传递到子容器视图控制器

时间:2019-12-07 15:24:18

标签: ios swift uiviewcontroller uicontainerview

我正在尝试使用容器将数据从ParentVC发送到childVC。该容器未嵌入,因为在我的应用中已多次使用该容器,因此无法使用prepareForSegue。我在ViewDidLoad中实例化containerVC。如何在加载时将数据传递到containerVC?我已经看到了关于从孩子传给父母的答案,但是不是这样。预先感谢您的帮助。

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

1 个答案:

答案 0 :(得分:3)

您可以像

一样尽早尝试
let childVC = storyboard!.instantiateViewController(withIdentifier: "ChildVC") as! ChildVC
childVC.boolVariable = true