Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: prepareForSegue with two different segues

Tags:

xcode

swift

segue

I have 2 UIButtons on a view. Each of them are linked to 2 different views. They have to pass different data depending which button you just tapped.

I know there is different way to segue but I want to use the prepareForSegue version for each (seems more clear for me to have the segue drawn on the storyboard and some code to explain what happened).

I tried this...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue != "historySegue") {
        let controller = segue.destinationViewController as! ResultViewController
        controller.match = self.match
    } else {
        let controller = segue.destinationViewController as! HistoryViewController
        controller.history = self.history
    }
}


@IBAction func showHistory(sender: UIButton) {
    performSegueWithIdentifier("historySegue", sender: self)
}

@IBAction func match(sender: UIButton) {
    performSegueWithIdentifier("matchSegue", sender: self)
}

But I got an error when I click the buttons

(lldb)

like image 367
Ragnar Avatar asked Jul 16 '15 14:07

Ragnar


Video Answer


2 Answers

Take out your IBActions (making sure to delete them in the Connections Inspector via the right side bar in the Interface Builder as well as in your code). For the segues, just use the Interface Builder, make sure both segue's identifiers are correct, then try this prepareForSegue method:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "matchSegue" {
        let controller = segue.destinationViewController as! ResultViewController
        controller.match = self.match
    } else if segue.identifier == "historySegue" {
        let controller = segue.destinationViewController as! HistoryViewController
        controller.history = self.history
    }
}
like image 131
Rachel Harvey Avatar answered Oct 13 '22 01:10

Rachel Harvey


You could switch it...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let identifier = segue.identifier {
        switch identifier {
        case "matchSegue":
            let controller = segue.destinationViewController as! ResultViewController
            controller.match = self.match
        case "historySegue":
            let controller = segue.destinationViewController as! HistoryViewController
            controller.history = self.history
        }
    }
}
like image 39
Fogmeister Avatar answered Oct 13 '22 00:10

Fogmeister