【问题标题】:How to pass variable to a ViewController that is embedded in a Navigation Controller?如何将变量传递给嵌入在导航控制器中的 ViewController?
【发布时间】:2021-10-23 07:05:16
【问题描述】:

我想将数据从ViewController1 传递到ViewController2ViewController2 嵌入在 Navigation Controller 中(因为我有一个对应于 3 个子视图控制器的分段控件)。我的转场是直接从ViewController1Navigation Controller

我在ViewController1中尝试了以下操作:

ViewController2().testID = "test value"

ViewController2 中有以下内容:

var testID = ""

但是,当我在 ViewController2 中运行 print(testID) 时,testID 不会更新。

建议将数据从ViewController1 传递到ViewController2?非常感谢任何帮助/建议!

【问题讨论】:

    标签: ios swift uiviewcontroller uinavigationcontroller segue


    【解决方案1】:

    您可以通过覆盖 ViewController1 中的 prepare(for segue:) 函数来传递值

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        // Get the new view controller using segue.destination 
        guard let destination = segue.destination as? UINavigationController else {
            return
        }
    
        guard let finalDestination = destination.viewControllers.first as? ViewController2 else {
            return
        }
    
        finalDestination.testID = "Test Value"
    }
    

    【讨论】:

      【解决方案2】:

      NSUserDefaults 将始终有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-13
        • 2019-06-02
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多