如何在Viewer中添加ViewController?

时间:2019-05-31 08:30:49

标签: ios swift

我想将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应该显示在标题中。

2 个答案:

答案 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:

  1. controller - it is the controller that you want to add as child to other controller
  2. containerView - 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.

相关问题