如何从自定义UITableview单元格获取表视图实例



我有一个带有自定义UITableViewCell的tableView,在该单元格类中,我想访问保存它的tableView。为此,我正在使用 cell.superView,它返回为 nil。但是当我不使用任何自定义UITableViewCell时,同样可以正常工作。

这是我的代码,

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? TestTableViewCell
    cell?.textLabel?.text = "Test"
    return cell!
}
class TestTableViewCell: UITableViewCell {
override func awakeFromNib() {
    super.awakeFromNib()
}
func loadDetails() {
    let tableView = self.superview //which is returning nil here
}}

UITableViewDelegate 上,当点击单元格时,您可以知道哪个UITableView包含它。

触发的方法为:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // tableView is the UITableView holding the cell.
}

正如其他人在评论中告诉您的那样,单元格可以访问tableView的属性不是一个好主意,因为单元格依赖于表。这意味着,如果您授予单元格权限以能够更改 tableView 中的属性,则两者都是依赖的,并且数百个单元格更改表中的属性可能会一团糟。因此,重新思考设计(即面向协议的编程)是个好主意。

但是如果没有其他可行的方法,那么您可以添加一个private weak var(我们需要它是私有的,以确保只有单元可以访问它,并且因为我们不想要保留周期而):

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TestTableViewCell
    cell.tableView = tableView
    cell.textLabel?.text = "Test"
    return cell
}
class TestTableViewCell: UITableViewCell {
    private weak var tableView: UITableView?
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    func loadDetails() {
        guard let tableView = tableView else { return }
        // Here you can access your tableView
    }
}

最新更新