簡體   English   中英

如何將 ViewController 添加到我的 Header 中?

[英]How can I add a ViewController into my Header?

我想將我的 ViewController 添加到我的OverViewController的標題中。 我寫了一個擴展來添加子視圖作為子視圖,但我不知道如何將它添加到我的ViewController的標題中。

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應該顯示在標題中。

您需要設置子視圖控制器的框架。

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)
    }
}

您需要提供要添加的childController和要添加childControllerparentControllerview ,即

extension UIViewController {
    func addChild(_ controller: UIViewController, in containerView: UIView) {
        self.addChildViewController(controller)
        controller.view.frame = containerView.bounds
        containerView.addSubview(controller.view)
    }
}

在上面的代碼中:

  1. controller -它是controller要添加為孩子其他控制器
  2. containerView - 要在其中添加childControllerparentControllerview

用法:

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)
        }
    }
}

在上面的代碼中,我添加了一個帶有identifier - VCcontroller identifier - VC作為containerView子級。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM