nayem nayem - 3 months ago 6
iOS Question

Loading different UIViews based on the data (precisely, different section) 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 each one of the cells, I'm segueing to an
UIViewController
and that segue has an identifier. Now, I need to load different contents (i.e.
UILabel
,
UIButton
) based on the section that I touched before in 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

Answer

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")
    }
}
Comments