我想将ViewController添加到OverViewController
的标题(在图像中显示为红色框)。我编写了一个扩展程序以将子视图添加为子视图,但是我不知道如何将其添加到ViewController
的标题中。 This是我的OverViewController
。
extension UIViewController {
func add(_ child: UIViewController) {
//add Child View controller
addChildViewController(child)
//add Child View as subview
view.addSubview(child.view)
//notify Child View Controller
child.didMove(toParentViewController: self)
}
}
ViewController
应该显示在标题中。
答案 0 :(得分:1)
您需要设置子视图控制器的框架。
extension UIViewController {
func add(_ child: UIViewController) {
//add Child View controller
addChildViewController(child)
//add Child View as subview
view.addSubview(child.view)
//set the frame of the child view
child.view.frame = view.bounds
//notify Child View Controller
child.didMove(toParentViewController: self)
}
}
答案 1 :(得分:1)
You need to provide both the childController
you want to add and the view
of parentController
in which you want to add the childController
, i.e.
extension UIViewController {
func addChild(_ controller: UIViewController, in containerView: UIView) {
self.addChildViewController(controller)
controller.view.frame = containerView.bounds
containerView.addSubview(controller.view)
}
}
In the above code:
controller
- it is the controller
that you want to add as child to other controllercontainerView
- the view
of parentController
in which you want to add the childController
Usage:
class ViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
if let controller = self.storyboard?.instantiateViewController(withIdentifier: "VC") {
self.addChild(controller, in: self.containerView)
}
}
}
In the above code, I'm adding a controller
with identifier - VC
as child to containerView
.