问题
I have a view controller with UITableView. The table data is populated using 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)
and I have the following delegate function:
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
}
I want to access the cell object from inside heightForRowAt
but it gives me nil
. Is there a way to access the cell here? I have been looking at UITableView+Rx.swift in RxCocoa project but there is no function for this. What other options do I have?
EDIT: I am trying to achieve the following in my code:
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:
The call tableView.cellForRow(at: indexPath)
returns nil in tableView(_: heightForRowAt:)
because heightForRowAt is called on a particular indexPath before the cellForRowAt is called.
The best bet here would be to use self-sizing cells. (https://www.raywenderlich.com/129059/self-sizing-table-view-cells). Another option would be to keep the size of the cells as part of your model and access them here.
来源:https://stackoverflow.com/questions/43015448/rxswift-uitableviewcell-how-to-get-cell-object-in-heightforrowat