swift - 访问另一个 View Controller 中的变量 - Xcode 8.0 Swift 3.0

标签 swift xcode uiviewcontroller segue

如何在一个 VC 上设置变量,然后在另一 VC 上访问它?我知道你需要使用prepare for segue,但我想在VC出现时访问变量。这是我到目前为止的代码:

override func viewDidAppear(_ animated: Bool) {

    print("viewDidAppear")

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        print("prepare for segue")

        let variableUnwind = ("StackOverFlow")

        if segue.identifier == "toFirstViewController"  {

            let hello = segue.destination as! AddItemViewController

            print(hello.username)



        }

    }

}

我知道准备转场意味着该函数中的操作将在转场之前发生,但我不知道如何消除准备转场而不丢失该函数中将发生的事情。

基本上,我想在 VC2 上设置一个变量,并在 VC1 加载后在 VC1 上访问它。如果有帮助的话,我正在使用展开转场从 VC2 转到 VC1。

最佳答案

你需要做

hello.无论你的变量名称是什么=你在VC2上创建的新变量

声明 hello 变量之后

希望这有帮助

override func viewDidAppear(_ animated: Bool) {
print("viewDidAppear")

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    print("prepare for segue")

    let variableUnwind = ("StackOverFlow")

    if segue.identifier == "toFirstViewController"  {

        let hello = segue.destination as! AddItemViewController

hello.variableName = newVariableName

    }

}

}

关于swift - 访问另一个 View Controller 中的变量 - Xcode 8.0 Swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074567/

相关文章:

ios - 使用 Swift 3D 触摸力值改变声音的音量

ios - 核心数据最佳实践——我在利用 C.D.正确有效? - iOS swift

ios - 如何检测弹出窗口中的点击事件? ( swift )

ios - 开关在 SMSegmentViev 中不起作用

ios - 使用Xcode5.1 beta5还是使用xcode 5.0.2部署?

ios - 如何在 ios swift 中以编程方式将 Storyboard View Controller 加载到标签栏 Controller 中?

ios - 无法将 UISegmentedControl 与三个选项卡和 ContainerView 一起使用

按下 UIButton 时,Swift 将文本保存到实例/全局变量

iOS UIViewController 无法打开另一个 uivewcontoller

ios - 在 iOS 中设置全局变量后,我的应用程序崩溃了