Alek Piasecki Alek Piasecki - 18 days ago 11
iOS Question

How to get didSelectRowAt IndexPath to differentiate between sections?

I have a set up that transfers info (the index for the cell selected) in a tableViewController so that the destination UIViewController can display some text info on a label by calling the appropriate index from an array. This all works correctly. However, there are 3 sections and I want the destination UIViewController to know which section was selected. (Ie. selecting the first cell in section 1 and the first cell in section 2 both return an index of 0, but I need it to be differentiable). I thought of passing the value of the selected section (and then setting up an if/else statement in the destination UIViewController) but I am not sure how to do that appropriately.
Here is the current code I have for the non-differentiating index pass:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow
let rowSelectedd = indexPath?.row
let destViewController: Controller = segue.destination as! Controller
destViewController.rowSelected = rowSelectedd!
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "rowSelected", sender: rowSelectedd)
}


Basically, how do I pass the value of the section of the selected cell?

Answer

If the destination controller needs both the row and section of the selected row, then use an IndexPath property instead of an Int property and pass the whole indexPath instead of just indexPath.row.

But why does the destination controller need to know the index path? That makes no sense. Why not pass the actual data for that index path (from your data model) to the destination controller?

Comments