【发布时间】: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