Swift; delegate embedded view controller and parent

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 16:52:48

What I ended up doing is adding this to the MainController:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "mySegue") {
        let vc = segue.destinationViewController as! EmbeddedController
        vc.delegate = self
    }
}

In storyboard I selected the segue from the MainController to the EmbeddedController, and set the identifier to "mySegue".

Without the code above the delegate kept returning nil. I didn't look into this solution at first as I thought segues were only for transitioning between view controllers, and in my mind I didn't see the embedded controller as a transition. Maybe someone more knowledgable than me (which is practically anyone on here at this point) can explain how this is all fitting together.

In any case, this is how I solved my issue and hopefully someone else can benefit from this as well :)

First of all, to avoid strong reference cycles:

protocol ControllerDelegate: class {
    func hideContainerView()
}

class EmbeddedController: UIViewController {
    weak var delegate: ControllerDelegate?

And you haven't added your newly instantiated VC view to container view, and not added it as a child VC:

        let vc = EmbeddedController()
        vc.delegate = self
        containerView.addSubview(vc.view)
        self.addChildViewController(vc)
        vc.didMoveToParentViewController(self)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!