使用自定义 UITableViewCell 时检测 UIButton

Detect UIButton while using custom UITableViewCell

我想实现一个由标签、按钮和图像等子视图组成的自定义 UITableViewCell class。这些单元格将显示使用 API 从网络上获取的内容。

我不想实现 UITableView 委托方法 didSelectRowAtIndexPath,因为这会使整个单元格都可选择。只有单元格中的按钮才能触发任何操作。

按钮通过 IBOutlet 从故事板连接到自定义 UITableViewCell。在 UITableViewController class 的 cellForRowAtIndexPath 中的 UIButton 上调用了 addTarget(_:action:forControlEvents:) 方法。

当我们想要在按钮的Selector 函数中检测所选单元格的indexPath 时,就会出现障碍。

这就是如何在选择器函数中检测到所选单元格的 indexPath

@IBAction func doSomething(sender: AnyObject) {
    var location: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    var indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(location)!
    println("The indexPath for Selected Cell is - \(indexPath.row)")
}

虽然这成功地解决了这个问题,但我的问题是;

1) 您是否找到了一种能够使用 UIButtons 在自定义 UITableViewCell 中传递所选单元格数据的替代方法?

2) 到目前为止,在 Swift 中实现类似场景的最佳实践是什么?

一种方法是遍历发送者的超级视图并查看是否可以找到 UITableViewCell...

假设您使用一种方法创建了一个通用 UIView 扩展,该方法会检查其父视图是否是 UITableViewCell...

extension UIView {
    func parentTableViewCell() -> UITableViewCell? {
        var view = self
        while let superview = view.superview {
            if let cell = superview as? UITableViewCell {
                return cell
            } else {
                view = superview
            }
        }
        return nil
    }
}

然后您可以执行以下操作...

if let cell = (sender as UIView).parentTableViewCell() {
    let indexPath = tableView.indexPathForCell(cell)
    println("The row for this cell is - \(indexPath.row)")
}

另一种方法是通过将视图设置为 Int 来使用视图的 tag 属性,然后检查发件人的 tag 在方法中的内容.

即在你的 tableView:cellForRowAtIndexPath: 方法中

cell.myButton.tag = indexPath.row

然后在你的doSomething方法中

let rowIndex = (sender as UIButton).tag
println("The row for this cell is - \(rowIndex)"

如果你的tableView只有一个section,可以使用button的tag 属性来存储indexPath.row.

cellForRowAtIndexPath中,当您为按钮设置目标操作时,设置button.tag = indexPath.row

然后在你的doSomething例程中:

@IBAction doSomething(sender: UIButton) {
    println("This button is from row - \(sender.tag)")
}