Passing variables between View Controllers using a segue

心不动则不痛 提交于 2019-11-30 03:17:43
Donn

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

class YourSecondViewController: UIViewController {
    var duration:Double?
}

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)
    }
}

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
    }
}

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.

SWIFT 3 From Swift 3, the method prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) has changed to prepare(for segue: UIStoryboardSegue, sender: Any?)

Steve Rosenberg

In the first ViewController place this (for modal segue):

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let theDestination = (segue.destinationViewController as ViewController2)
    theDestination.Duration2 = Duration
}

Change ViewController2 to the name of the second ViewController. In ViewController2 create a class variable:

var Duration2 = (whatever the type - UInt8 I guess for time)

That's it. You will have in the value of Duration2 the value of Duration from the first ViewController.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!