【问题标题】:RxSwift + UITableViewCell how to get cell object in heightForRowAtRxSwift + UITableViewCell 如何在 heightForRowAt 中获取单元格对象
【发布时间】:2017-03-25 10:49:47
【问题描述】:

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

【问题讨论】:

  • 在模型中添加必要的参数,并从数据源数组中获取信息。
  • 我在单元格类中有一个计算单元格高度的函数。我将有多个原型单元,所以我想统一它。因此,将该功能放在作为业务逻辑一部分的模型中是不明智的。
  • 请检查我的编辑以获得澄清。
  • 无论如何heightForRow 被称为之前 cellForRow 这就是你得到nil 的原因。
  • @Gasim 谢谢你。我已经确认了同样的行为。我认为单元格类型会进入 ViewModel 很奇怪,但我理解。

标签: swift uitableview rx-swift rx-cocoa


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-06-24
    • 1970-01-01
    • 2017-09-05
    • 2013-02-06
    • 2021-06-21
    • 1970-01-01
    • 2011-10-20
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多