使用segue在视图控制器之间传递变量 [英] Passing variables between View Controllers using a segue

查看:81
本文介绍了使用segue在视图控制器之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Swift和Xcode 6,并希望使用Segue将变量从一个View Controller传递给另一个。

I use Swift and Xcode 6 and would like to pass a variable from one View Controller to another using a Segue.

我创建了一个名为'MainToTimer'的segue一旦按下按钮就会触发。我希望能够在第二个View Controller上使用名为'Duration'的变量。

I have created a segue called 'MainToTimer' which is trigger once button is pressed. I would like to be able to use the variable called 'Duration' on the second View Controller.

是否可以传递多个变量和常量?

Is it possible to pass multiple variables and constants?

我需要为每个View Controller关联哪些代码?

What code do I need associated to each View Controller?

提前谢谢你。

推荐答案

首先,设置属性/属性以将变量保存在第二个视图控制器(目标)中。

First, setup property/properties to hold your variables in your second view controller (destination).

class YourSecondViewController: UIViewController {
    var duration:Double?
}

然后按下按钮触发自定义segue。使用你的变量('duration')作为发送者的参数。

Then have your button trigger your custom segue. Use your variable ('duration') as the argument for sender.

class YourFirstViewController: UIViewController {
    @IBAction func buttonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("MainToTimer", sender: duration)
    }
}

最后,通过覆盖prepareForSegue方法传递此发件人数据:

Finally, pass this sender data by overriding the prepareForSegue method:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "MainToTimer") {
        let secondViewController = segue.destinationViewController as YourSecondViewController
        let duration = sender as Double
        secondViewController.duration = duration
    }
}

是,也可以使用prepareForSegue的'sender'参数传递多个变量和常量。如果您要传入多个数据,请将它们放在一个数组中,并将该数组作为发送方。

Yes, it is also possible to pass multiple variables and constants, again using the 'sender' parameter of prepareForSegue. If you have multiple data you want to pass in, put them in an array and make that array the sender.

这篇关于使用segue在视图控制器之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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