Search code examples
iosswiftuitableviewsegueuistoryboardsegue

SWIFT: Connect UITableViewCell to two different detail view controllers


Suppose I have a SWIFT app and it contains a UIViewController with a table. The table of course has prototype UITableViewCells. The information contained in the cell can be one of two internal object types, lets say Widget and Sprocket. Widget and Sprocket are objects that derive from the same base class Thing.

My table will be a list of Things, where each Thing is either a Widget or a Sprocket. What I want to happen is that if a user selects a table cell that is a Widget, it should show a details ViewController for a Widget, ie WidgetViewController. If however the user selects a Sprocket then the app should show a SprocketViewController.

How exactly can I make this happen? My understanding is that if I go into the storyboard and click-drag to make a segue from the main VC to either WidgetViewController or SprocketViewController then that segue will occur in the app automagically, ie without me adding any code. So if I click-drag to create two such segues then I have no idea what will happen but I assume that the app will crash from trying to call both segues.

The problem I am facing is that my current app has a WidgetTableViewController with a storyboard segue to a WidgetViewController and also has a SprocketTableViewController with a storyboard segue to a SprocketViewController, but now I have to put Widgets and Sprockets into the same VC (ie ThingTableViewController) and have the app conditionally launch either WidgetViewController or SprocketViewController.

So how do I do this?


Solution

  • One way to do this could be:

    In the tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function of your UITableViewDelegate check if the selected cell corresponds to an object Widget or an object Sprocket

    Then, present the corresponding UIViewController with the necessary configuration with this code:

    let vc = UIStoryboard(name: "The name of your storyboard here", bundle: nil).instantiateViewController(withIdentifier: "Your VC identifier") as! YourViewController
    // pass your data and configure the viewcontroller here
    navigationController?.pushViewController(vc, animated: true)
    

    In storyboard, assign the identifier that you think is convenient to your ViewController:

    Select the ViewController -> 3rd item -> Identity -> StoryboardId and check "Use Storyboard ID"

    Note: Delete the segues what are you currently using