Search code examples
iosobjective-cuitableviewsegue

How to load different UIViews based on different data after segueing from an UITableView?


I've an UITableView which loads data from a database file. It has different sections. I have managed to design a custom UITableViewCell programmatically. When I touch a cell, I'm segueing to an UIViewController. The segue is added from the Interface Builder. Now, I need to load different contents (i.e. UILabel,UIButton) in the new UIViewController based on the section number of the UITableView. For more visualization, I'm adding images below.

How to accomplish this? Should I use custom UIViewController subclass for each action? Or is there any easier way to do this?

1st view

view 1

2nd view

view 2

3rd view

view 3


Solution

  • In code, you can use the prepareForSegue method, check the identifier, and pass the next UIViewController the relevant data.

    If the interface is different for each kind cell, then you should use different UIViewControllers for each kind of interface. All of this can be done through the storyboard, by "ctrl-dragging" from each prototype cell to a different controller.


    If you don't want to use different prototype cells for different data. (Which would make this very easy to do with the Storyboard), then instead of segueing through the storyboard, call the segue via code in the didSelectRowAtIndexPath method of your UITableView delegate. Like this:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch indexPath.section {
        case 0:
            performSegueWithIdentifier("some_segue_id", sender: self)
        case 1:
            performSegueWithIdentifier("another_segue_id", sender: self)
        default:
            print("not a known section")
        }
    }