Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a custom cell is selected from within the cell itself?

I have created a custom UITableViewCell (along with an XIB for layout within the storyboard designer). I understand how the parent tableview notifies on cell selection by triggering didSelectRowAtIndexPath, but I can't seem to figure out how to catch the selection of a cell within the cell itself. Can someone point me in the right direction here? Im using XCode 8 and Swift 2. Thanks!

Here is my simple custom cell class with the stubbed function to handle when the cell is selected:

class MyCustomCell: UITableViewCell {
  func didSelect(indexPath: NSIndexPath ) {
    // perform some actions here
  }
}
like image 813
Paul Avatar asked Dec 19 '22 10:12

Paul


1 Answers

What you could do is listen for didSelectRowAtIndexPath on the UITableView, and then call a function in the cell. Here's an example:

class MyCustomCell: UITableViewCell {
    func didSelect(indexPath: NSIndexPath) {
        // perform some actions here
    }
}

Then, in your didSelectRowAtIndexPath:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell {
        cell.didSelect(indexPath: indexPath)
    }
}
like image 86
TajyMany Avatar answered May 10 '23 13:05

TajyMany