RxSwift + UITableViewCell如何在heightForRowAt中获取单元格对象

问题描述 投票:4回答:1

我有一个UITableView视图控制器。使用RxSwift填充表数据:

let observable = Observable.just(data)
observable.bindTo(tableView.rx.items(cellIdentifier: "CategoryCell", cellType: CategoryCell.self)) { (row, element, cell) in
    cell.setCategory(category: element)
}.disposed(by: disposeBag)

tableView.rx.setDelegate(self).disposed(by: disposeBag)

我有以下委托功能:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // cell = nil. 
    let cell = tableView.cellForRow(at: indexPath)

    let screenWidth = UIScreen.main.bounds.size.width

    let itemWidth = (screenWidth / 3.0) - 20
    let itemHeight = (itemWidth) / 0.75 + 110

    return itemHeight
}

我想从heightForRowAt内部访问单元格对象,但它给了我nil。有没有办法在这里访问单元格?我一直在RxCocoa项目中查看UITableView + Rx.swift,但没有这个功能。我还有其他选择吗?

编辑:我试图在我的代码中实现以下内容:

class CategoryCell : UITableViewCell {
     func calculateHeight() {
        let screenWidth = UIScreen.main.bounds.size.width

        let itemWidth = (screenWidth / 3.0) - 20
        let itemHeight = (itemWidth) / 0.75 + 110

        return itemHeight
     }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // cell = nil. 
    guard let cell : CategoryCell = tableView.cellForRow(at: indexPath) as? CategoryCell {
         return 0.0
    }
    return cell.calculateHeight()
}
swift uitableview rx-swift rx-cocoa
1个回答
2
投票

调用tableView.cellForRow(at: indexPath)tableView(_: heightForRowAt:)中返回nil,因为在调用cellForRowAt之前,在特定的indexPath上调用heightForRowAt。

这里最好的选择是使用自定尺寸单元格。 (https://www.raywenderlich.com/129059/self-sizing-table-view-cells)。另一个选择是将单元格的大小保持为模型的一部分并在此处访问它们。

© www.soinside.com 2019 - 2024. All rights reserved.