【问题标题】:Swift 4 How to pass data between ViewControllers and ContainerViews?Swift 4 如何在 ViewControllers 和 ContainerViews 之间传递数据?
【发布时间】:2019-10-20 14:09:48
【问题描述】:

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

如上图所示,ViewController C 有一个清晰的背景,使得在 ViewController A 和 B 的 UIView 中都可以看到“Test Label”。

当我从 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 中添加一些东西吗?

【问题讨论】:

标签: ios swift uicontainerview


【解决方案1】:

正确,您必须在原始视图控制器中使用 prepare(for segue:..) 覆盖,它将 ViewController B 的实例作为 segue.destination 传递。

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if let viewControllerB = segue.destination as? ViewControllerB
    {
        viewControllerB.testLabel.text = "Some new text"
    }
}

查看本教程了解更多信息:https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/

【讨论】:

  • 嗯是有道理的,这就是我的想法,但后来 Hossam 的回答澄清了一切。感谢您的帮助!
【解决方案2】:

您可以为从容器到 viewController C 的嵌入 segue 提供一个标识符,比如 embedSegueFromBToC,然后在父控制器中的 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"
            }
        }
    }

【讨论】:

  • 起床试试这个.. 非常感谢!完美运行!
猜你喜欢
  • 1970-01-01
  • 2017-12-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多