有两个视图控制器MainViewController
和ChildViewController
,我想将ChildViewController
添加到MainViewController
,这是我的代码:
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组件。
答案 0 :(得分:2)
self.add(ChildViewController(), in: containerView)
您正在以编程方式创建ChildViewController
实例,而不是从情节提要中获取它。
if let childViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") {
self.add(ChildViewController(), in: containerView)
}