Search code examples
xcodeswiftsegue

Swift: prepareForSegue with two different segues


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)


Solution

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