在容器视图中设置代理

时间:2018-11-12 05:37:00

标签: ios swift delegates

我的情节提要中有一个容器视图,其中显示了另一个我已经编程并填充的视图控制器。我想在主视图控制器和包含视图的控​​制器之间进行通信。我知道如何使用委托,并且对使用它们感到很满意,但是通常我在初始化ViewController时会设置委托,但是在这种情况下,我不知道在哪里应用此委托,因为每个情节提要中都有视图控制器。通常我会做这样的事情:

class HomeVC: UIViewController {
    func initializeVC() {
        resultsVC = self.storyboard?.instantiateViewController(withIdentifier: "resultsView") as! GoalsVC
        resultsVC.calcDelegate = self //I set the "HomeVC" as the Delegate since it has all the functions I need
    }
}

如上所述,由于我从未真正通过代码创建此视图控制器,所以我不知道如何分配委托(特别是将委托设置为“ self”(其中Self是主要的View Controller)

2 个答案:

答案 0 :(得分:1)

将故事板用于容器视图时。有一个segue类型的embed。给这个segue一个identifier,例如MyContainedViewControllerSegueId

然后在prepare(for segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MyContainedViewControllerSegueId" {
            // here you get your contained view controller as `segue.destination`
            // cast it your subclassed view controller
            // use delegate on that subclassed view controller for communication purpose.
        }
    }

答案 1 :(得分:1)

您可以在prepareforsegue中分配代表。像下面的代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "container_segue") {
        let controller = segue.destination as! containerController
        controller.delegate = self
    }
}

项目运行时,此方法会自动调用,因为我们已在情节提要中创建了segue。

通过使用segue.identifier,您可以检查将要发生哪个控制器锁定,并因此可以满足您的要求。