gpt4 book ai didi

swift - Swift 中 Container View 和 ViewController 之间的委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 10:08:54 25 4
gpt4 key购买 nike

我问的是question before ,我得到了他所寻求的解决方案。现在,我需要扩大我的问题。 使用委托(delegate),如何创建一个委托(delegate),让 ViewController 向 ContainerView 发送数据,以及 ContainerView 向 ViewController 发送数据

最佳答案

嗯,我不知道这是否完全是您正在寻找的,但在这种情况下我一直所做的就是在另一个类中保留每个 View Controller 的记录。

例如,如果您的容器 View 具有带有标识符“Embed Segue”的嵌入segue,那么您的类可能如下所示:

super View 类

Class ViewControllerOne: UIViewController {
var data = "This is my data I may want to change"
var subView: ViewControllerTwo?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Embed Segue" {
let destinationVC = segue.destinationViewController as! ViewControllerTwo
destinationVC.superView = self
self.subView = destinationVC
}
}
}

嵌入式类

Class ViewControllerTwo: UIViewController {
var data = "This is the other view controller's copy of that data"
var superView: ViewControllerOne?
}

然后,您只需分别引用 self.subView.dataself.superView.data 即可在这些 View Controller 之间传递数据。

编辑:对于 ViewControllerTwo 将数据传递回 ViewControllerOne,只需引用 self.superView.data 即可。例如:

Class ViewControllerTwo: UIViewController {
var data = "This is the other view controller's copy of that data"
var superView: ViewControllerOne?

func passDataBack() {
self.superView.data = self.data
}
}

这将更新第一个 View Controller 中的数据变量。

关于swift - Swift 中 Container View 和 ViewController 之间的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34305352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com