有两个视图控制器,MainViewControllerChildViewController,我想将ChildViewController添加到MainViewController,这是我的代码:
主视图控制器.swift

class MainViewController: UIViewController {

    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.add(ChildViewController(), in: containerView)
    }

}

ChildViewController.swift子视图控制器
class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("ChildViewController is loaded")
    }

}

UIViewController+Ext.swift
extension UIViewController {
    func add(_ child: UIViewController, in container: UIView) {
        addChild(child)
        container.addSubview(child.view)
        child.view.frame = container.bounds
        child.didMove(toParent: self)
    }

    func add(_ child: UIViewController) {
        add(child, in: view)
    }

    func remove(from view: UIView) {
        guard parent != nil else {
            return
        }

        willMove(toParent: nil)
        removeFromParent()
        view.removeFromSuperview()
    }

    func remove() {
        remove(from: view)
    }
}

故事板
ios - iOS:添加 subview  Controller 不会显示子组件-LMLPHP
输出:
ios - iOS:添加 subview  Controller 不会显示子组件-LMLPHP
终端中显示“ChildViewController is loaded”,但未加载UI组件。

最佳答案

self.add(ChildViewController(), in: containerView)

您正在以编程方式创建一个ChildViewController实例,而不是从脚本获取它。
if let childViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") {
    self.add(ChildViewController(), in: containerView)
}

10-08 05:47