ios - 使用 segue 在 View Controller 之间传递变量

标签 ios xcode swift segue xcode6

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

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

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

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

提前致谢。

最佳答案

首先,设置属性/属性以将变量保存在第二个 View Controller (目标)中。

class YourSecondViewController: UIViewController {
    var duration:Double?
}

然后让您的按钮触发您的自定义转场。使用您的变量(“持续时间”)作为发件人的参数。

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

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

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”参数。如果您有多个数据要传入,请将它们放在一个数组中,并使该数组成为发送方。

SWIFT 3 从 Swift 3 开始,方法 prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) 已更改为 prepare(for segue: UIStoryboardSegue, sender: Any?)

关于ios - 使用 segue 在 View Controller 之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25597820/

相关文章:

ios - 搜索栏不会出现在 ios 中

iPhone : initing plist field value with the value of another field

iOS MapKit 获取地点信息和评论

ios - IOS 新手,我手机上的应用程序与模拟器不同

ios - 在 Swift 中如何将值传递给 API?

swift - Firebase 存储 downloadURL 部分应用 @nonobjc 消息的转发器

ios - 如何创建适用于 Retina 显示的 CGBitmapContext 而不会浪费常规显示空间?

python - Cocoa 应用程序无法开始循环 python 脚本。通过 xcode 构建/运行时有效

iphone - 没有规则处理架构armv6的文件

ios - UILocalNotification:播放保存在文档目录中的自定义音频文件