UITableView didSelectRowAtIndexPath get instance of selected section

manu picture manu · Mar 8, 2016 · Viewed 16k times · Source

Is there a way to get the instance of the section in which a row was selected? It is possible to get the index of the section, the index of the selected cell, the instance of the selected cell..but the instance of this section?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow // index path of selected cell

    let headerCellIndex = indexPath!.section // index of selected section
    let headerCellName = ????? // instance of selected section

    let cellIndex = indexPath!.row // index of selected cell
    let cellName = tableView.cellForRowAtIndexPath(indexPath!) //  instance of selected cell
}

Thank you.

Answer

Ted Huinink picture Ted Huinink · Mar 8, 2016

This always worked well for me. I always unwrap it as well optionally to the class I assigned to it just to make sure I have the right type of cell. In this example I have MyTableViewCell but it can of course be anything.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   if let cell = tableView.cellForRow(at: indexPath) as? MyTableViewCell {
         print(cell.label.text!)
    }
}