Luciano
Luciano

Reputation: 31

Calling prepareforSegue from a UIButton?

I am trying to call a prepareForSegue function out of TableViewController from a button in an UITableViewCell.

Can I just call it from the button? Something like:

TableViewcontroller:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "segueExercise") {
            print(segue.identifier)
        let vc = segue.destinationViewController as! DetailViewController

TableViewCell:

@IBAction func exerciseAction(sender: UIButton) {
    ViewController.prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
}

Would it be too easy, or am I missing something ?

Upvotes: 2

Views: 1785

Answers (3)

Luciano
Luciano

Reputation: 31

Solved. I passed the index via UIButton option tag and replaced the indexPathForSelectedRow.

Upvotes: 0

Haole Jon
Haole Jon

Reputation: 31

Yes, you can, but you need to override the prepareForSegue() func. This is used if you are using a 'code only' segue, and can be used to pass values to the new view controller. For example, this is for a 'Roshambo' game that uses three buttons, one with code only, one with storyboard and code, and one with storyboard only. One prepareForSegue() is used to select the value to be passed based on which button calls for the segue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let nextController = segue.destinationViewController as! RoshamboViewController
nextController.opponentValue = self.randomRoshambo()
//determine which segue called prepareForSeque
if (segue.identifier == "choosePaper") {
    nextController.playerValue = "paper"}
else if segue.identifier == "chooseScissors"{
    nextController.playerValue = "scissors"}

Upvotes: 0

Nerkyator
Nerkyator

Reputation: 3976

PrepareForSegue is automatically triggered when you call performSegueWithIdentifier (or by Storyboard connecting two UIView CTRL-dragging from first UIView to second UIView). You can't call it "manually"

Upvotes: 7

Related Questions