Reputation:
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.
Upvotes: 3
Views: 17489
Reputation: 856
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!)
}
}
Upvotes: 13
Reputation: 71
With function DidSelectRows you can use a switch like this (Ex. 3 Sections, variable Rows)
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
Action to do with first cell (ex. performSegue(withIdentifier: "", sender: nil)
case 1:
Action to do with second cell
default:
break
}
case 1:
Things you want to do in the second section
case 2:
Things you want to do in the third section
default:
break
}
Upvotes: 3
Reputation: 5712
or Swift 3.0, use
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
//your code...
}
Upvotes: -1