Passing data with Segue and populating different views

I want to pass some data to a segue.

I have a table view controller with different sections and each section has a different type of cell (loaded with nibs).

I now added that when you click on a cell it displays more information about it (notice that different cells have different amounts of info to display). This means that I click on a cell, get its section, use appropriate segue with specific id.

Now, I want to display the data in this new view loaded with the segue.

A problem arises. How do I forward the cell data with the segue?

And most importantly, do I really need to make an .h and .m file for each type of view? I would need to access the placeholder labels and change them with the proper data, so this seems the case.

This seems cumbersome. The info shown for each cell has to do the same exact thing, and has the same methods (for example color changing if the dark mode is enabled), except for different labels (some require more, some require less).

Is this the only way of doing this?

1 answer

  • answered 2018-10-12 07:58 TomQDRS

    In order to pass data to another ViewController on the other end of a segue, override prepare(). Use segue.destination to get the next ViewController. You can use segue.identifier to check which segue is being called, and then get the destination resolved as the class you know it to be.

    Now that you have your destination ViewController, you can set parameters you defined in its class. Let's say your class looks like this:

    class MyInfoViewClass: UIViewController {
       var title: String?
    } 
    

    Then you can set the title property via prepare() like so:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "mySegue") {
            let infoView = segue.destination as! MyInfoViewClass
            infoView.title = "TitleInformation"
        }
    }
    

    As for your second question, I don't see what your problem is - If the two views display the same info and act generally the same, then call the same view from both cells and set the respective info as its variables. That's kinda the whole point of the class concept.