有两个视图控制器,MainViewController
和ChildViewController
,我想将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)
}
}
故事板
输出:
终端中显示“
ChildViewController is loaded
”,但未加载UI组件。 最佳答案
self.add(ChildViewController(), in: containerView)
您正在以编程方式创建一个
ChildViewController
实例,而不是从脚本获取它。if let childViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") {
self.add(ChildViewController(), in: containerView)
}