RxSwift + UITableViewCell如何在heightForRowAt中获取cell对象

4

我有一个带有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()
}

1
无论如何,heightForRowcellForRow之前被调用,这就是为什么你得到了nil - vadian
我遇到了相同的问题/困惑 - @gasim。你找到解决方案了吗? - bleeckerj
@bleeckerj 这里的问题是在cellForRow之前调用了height。由于我的布局并不复杂(顶部有一个封面和一堆集合视图;全部都在tableview中),我只是根据indexPath来完成它。为了使其更加灵活,我认为您需要将单元格类型存储在ViewModel中(如果您使用MVC,则为Model)。否则,其他任何方法都会很困难。 - Gasim
1
@Gasim感谢您的建议。我已经确认相同的行为。我觉得单元格类型放在ViewModel中很奇怪,但我理解。 - bleeckerj
你可以将表视图的rowHeight属性设置为UITableViewAutomaticDimension,让单元格自适应大小吗? - Paul
显示剩余4条评论
1个回答

2
电话tableView.cellForRow(at: indexPath)tableView(_: heightForRowAt:)中返回nil,因为heightForRowAt是在调用cellForRow之前针对特定的indexPath 调用的。
在这里最好的选择是使用自动调整大小的单元格(self-sizing cells)。(https://www.raywenderlich.com/129059/self-sizing-table-view-cells)。另一个选项是将单元格的大小作为您模型的一部分并在此处访问它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接