2
votes

I am trying to accomplish something that seems simple enough: I have a UITableView with dynamic UITableViewCells. When each cell is selected, I want to perform a segue to a different view controller in my Storyboard. However, I want to create the segues programatically because I want to determine which ViewController gets called at runtime. However, I can't seem to get it to work.

Here's how I set up my code for the cell selection:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if(indexPath.row==0){

        var calculoViewController = CalculoViewController()
        var calcSegue = UIStoryboardSegue(identifier:"Menu_Calc", source: self, destination: calculoViewController)

        self.performSegueWithIdentifier("Menu_Calc", sender: self)
    }
    else
    {
        var deducVC = DeductionsViewController()
        var deducSegue = UIStoryboardSegue(identifier: "Menu_Deduc", source: self, destination: deducVC)
        self.performSegueWithIdentifier("Menu_Deduc", sender: self)
    }
}

However, this fails with: NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'Menu_Calc''

Note that I don't have any drawn segues in my Storyboard, that is why I am creating them dynamically. Previously I tried drawing them by connecting the prototype cell with the ViewControllers, but then every cell called the same segue, despite the code.

2
instead of performing a segue, push the ViewController on navigation stack programmatically - saurabh
I don't have a NavigationController set up on this Storyboard (though I admit, it's starting to look like a good idea to do it that way). - tutiplain
Yeah, just embed your ViewController in Navigation Controller and it'll become the root view controller. - saurabh

2 Answers

1
votes

The correct way to perform the segue you just created would be this

var calcSegue = UIStoryboardSegue(identifier:"Menu_Calc", source: self, destination: calculoViewController)
calcSegue.perform()

If you want to create segues using the storyboard but not called on row selection, you can create a segue between the 2 viewcontrollers (not the prototype cell and VC) and give them an identifier. Then in your didSelectRow method, perform the segue with the correct identifier.

0
votes

Wow it is mid of 2018 and the issue is still lack of a valid answer! I hope someone may provide a valid answer. I have more than two dynamic cells to more than two seguing-to view controllers.

Yet, for Tutiplain's simple situation - only one if-else, I would suggest to use normal reusable cell's segue in else block. For first row in his case, use shouldPerformSegue(withIdentifier:sender:) to prevent it from this normally seguing; then use performSegue(withIdentifier: sender:) to manually do a special segue that is set up on storyboard by ctrl-drag from controller icon of seguing-from view controller to segueing-to view controller.