检测何时从单元格本身中选择自定义单元格?

Pau*_*aul 4 xcode uitableview swift

我创建了一个自定义UITableViewCell(以及用于故事板设计器中的布局的 XIB)。我了解父 tableview 如何通过触发通知单元格选择didSelectRowAtIndexPath,但我似乎无法弄清楚如何在单元格本身内捕获单元格的选择。有人可以在这里指出我正确的方向吗?我正在使用 XCode 8 和 Swift 2。谢谢!

这是我的简单自定义单元格类,带有 stubbed 函数以在单元格被选中时进行处理:

class MyCustomCell: UITableViewCell {
  func didSelect(indexPath: NSIndexPath ) {
    // perform some actions here
  }
}
Run Code Online (Sandbox Code Playgroud)

Taj*_*any 7

你可以做的是didSelectRowAtIndexPath在 UITableView 上监听,然后在单元格中调用一个函数。下面是一个例子:

class MyCustomCell: UITableViewCell {
    func didSelect(indexPath: NSIndexPath) {
        // perform some actions here
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的didSelectRowAtIndexPath:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell {
        cell.didSelect(indexPath: indexPath)
    }
}
Run Code Online (Sandbox Code Playgroud)