ios - 在容器 View 中设置委托(delegate)

标签 ios swift delegates

我的 Storyboard 中有一个容器 View ,它显示了另一个我已经编程和填充的 View Controller 。我想在主视图 Controller 和包含 View Controller 之间进行通信。我知道如何使用委托(delegate)并且我很乐意使用它们,但是我通常在初始化 ViewController 时设置委托(delegate),但是在这种情况下我不知道在哪里应用它,因为 View Controller 已经存在于 Storyboard中.通常我会做这样的事情:

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

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

最佳答案

您可以在prepareforsegue 中分配委托(delegate)。喜欢下面的代码

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

当项目运行时,这个方法会自动调用,因为我们已经在 Storyboard中创建了 segue。

通过使用 segue.identifier,您可以检查将要发生哪个 Controller segue,从而可以实现您的要求。

关于ios - 在容器 View 中设置委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256429/

相关文章:

ios - 如何使用关联类型协议(protocol)作为函数的参数类型?

ios - 带有延迟标题和消息的 actionSheet 样式警报

ios - 本地化的 ipad .nib 文件不起作用

swift - 如何检测 NSTextField 上的回车键命中

ios - 如何在 iOS 中绘制一个点?

objective-c - Objective-C 中的委托(delegate)查询

ios - 如何将数据传递到 UINavigationController 堆栈上的第 n 个 View Controller ?

ios - UITextfield 光标移动

swift - 仅运行一次 keyDown 函数

objective-c - id 类型实例变量向实例方法发送消息