gpt4 book ai didi

ios - Swift 4 如何在 ViewControllers 和 ContainerViews 之间传递数据?

转载 作者:行者123 更新时间:2023-11-28 13:37:16 26 4
gpt4 key购买 nike

我有 3 个 ViewController:ViewController A 和 ViewController B,以及 Controller C,它实际上是由两个 UIView 组成的 ContainerView

My Storyboard

如您在上图中所见,ViewController C 具有清晰的背景,因此可以在 ViewController A 和 B 的 UIView 中看到“测试标签”。

当我从 ViewController A 向上滑动到 ViewController B 时,我希望能够执行一些动画(淡入/淡出、翻译、更改文本等)。假设我想将文本从“测试标签”更改为“一些新文本”,问题是当我进入 ViewController B 时,我收到“在展开可选值时意外发现 nil”错误。

为什么我得到的是 nil 以及如何正确更改标签文本?

这段代码似乎有道理,但我无法正确理解:

let containerViewController = ContainerViewController()
containerViewController.testLabel.text = "Some new text"

我也试过:

let containerViewController = storyboard?.instantiateViewController(withIdentifier: "containerViewController") as! containerViewController


containerViewController.testLabel.text = "Some new text"

我是否必须在 ViewController A 的 override func prepare 中添加一些东西?

最佳答案

您可以为从容器到 viewController C 的嵌入 segue 提供一个标识符,比如 embedSegueFromBToC 然后在父 Controller 的 prepare for segue 中捕获实际的 ViewController C假设 B

所以在 B viewController 中添加:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "embedSegueFromBToC" {
if let viewControllerC = segue.destination as? ViewControllerC {
viewContrllerC.loadViewIfNeeded() // you might need this since the need to access the testLabel which a UI component that need to be loaded
viewControllerC.testLabel.text = "Some new text"
}
}
}

关于ios - Swift 4 如何在 ViewControllers 和 ContainerViews 之间传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56454153/

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