使用Segue发送变量 [英] Sending Variables with a Segue

查看:93
本文介绍了使用Segue发送变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的iOS Swift应用.该应用程序有2个视图控制器和一个已编程为与另一个视图控制器相连的按钮,如下所示:

I am working on a simple iOS Swift app. The app has 2 view controllers and a button that has been programmed to segue to the other view controller like so:

@IBAction func pushMe(sender: AnyObject) {
        self.performSegueWithIdentifier("changeIt", sender: nil)
}

上面的工作,但我希望能够从当前的视图控制器中保存2个变量,并使它们可供我所选择的视图控制器使用.所以我这样做了:

The above works but I want to be able to save 2 variables from the current view controller and make them available to the view controller I am segueing to. So I did this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "changeIt" {
        var testVar1 = "Hello"
        var testVar2 = "World"
    }
}

在我要添加的视图控制器中添加:

In the view controller that I am segueing to I added:

var testVar1:String!
var testVar2:String!

该应用程序正常运行,但是一旦我尝试访问testVar1或testVar2,该应用程序就会崩溃.我不确定为什么这没有按预期进行?

The app works but as soon as I try to access testVar1 or testVar2, the app crashes. I am not sure why this isn't working as intended?

推荐答案

由于未初始化变量,因此省略了目标视图控制器.使用下面的代码

Because variables were not initialized, you omitted destination view controller. Use the code below

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "changeIt" {
        let dvc = segue.destinationViewController as! YourDestinationViewController
        dvc.testVar1 = "Hello"
        dvc.testVar2 = "World"
    }
}

这篇关于使用Segue发送变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆