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



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

这是我的简单自定义单元格类,其中包含在选择单元格时处理的存根函数:

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

做的是在 UITableView 上侦听didSelectRowAtIndexPath,然后在单元格中调用函数。下面是一个示例:

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

然后,在您的didSelectRowAtIndexPath中:

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

好的。我明白你的意思。如果从其他任何位置选择单元格,则希望从自定义类中执行某些操作。右?

类中有一个属性:isSelected UITableViewCellBOOL 类型。参考:苹果文档链接

您可以通过调用 self 来检查此属性是否为真/假。然后,您可以在课堂中执行所需的操作。

这是 Objective-C 中的一个例子,因为我对 swift 不是很熟悉。但我认为每个人都可以得到这个:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
    if (self.selected) {
        NSLog(@"Whoa you selected a cell");
        // or perform your desired action
    }
}

在这里- (void)setSelected:(BOOL)selected animated:(BOOL)animated该方法等效于 swift 中的 setSelected(_:animated:)(检查:这里),每次您从任何地方选择单元格时都会自动调用它。

不太确定为什么需要做这样的事情,单元格的选择可以由UITableViewDelegate处理。 但是,如果您坚持将代码放在单元格类中,则可以在委托方法中调用didSelect didSelectRowAt如下所示:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    (tableView.cellForRow(at: indexPath) as? MyCustomCell).didSelect(indexPath)
}

通常处理选择的代码将直接出现在此方法中,但您可以像我上面所做的那样调用您的单元格。

最新更新