Skip to main content
 首页 » 操作系统

uitableview之使用自定义 UITableViewCell 时检测 UIButton

2024年01月01日34qq78292959

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

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

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

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

这就是如何在 Selector 函数中检测所选单元格的 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 中实现类似场景的最佳实践是什么?

请您参考如下方法:

一种方法是迭代发送者的 super View 并查看是否可以找到 UITableViewCell...

假设您使用一种方法创建了一个通用的 UIView 扩展,该方法会检查其父 View 是否是 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)") 
} 

另一种方法是通过将 View 的 tag 属性设置为 Int 来使用它,然后检查方法中发送方的 tag 是什么.

即在您的 tableView:cellForRowAtIndexPath: 方法中

cell.myButton.tag = indexPath.row 

然后在你的doSomething 方法中

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