Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables between View Controllers using a segue

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

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?

What code do I need associated to each View Controller?

Thank you in advance.

like image 783
DanteDeveloper Avatar asked Sep 01 '14 01:09

DanteDeveloper


People also ask

How do you add a segue between two view controllers in a storyboard?

The segue needs to connect from the view controller itself so nothing else triggers it. To create a segue from the controller Control-drag from the View Controller icon to the Exit icon. Give this new segue the identifier unwind to reference it from the code.


1 Answers

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

like image 123
Donn Avatar answered Sep 21 '22 09:09

Donn