RxSwift + UITableViewCell how to get cell object at heightForRowAt

I have a view controller with a UITableView. The table data is filled with 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 inside heightForRowAt

, but it gives me nil

. Is there a way to access the cell here? I have looked at UITableView + Rx.swift in RxCocoa project but there is no function for that. What other options do I have?

EDIT: I am trying to accomplish 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()
}

      

+3


source to share


1 answer


The call tableView.cellForRow(at: indexPath)

returns nil in tableView(_: heightForRowAt:)

because heightForRowAt is called at a specific indexPath before cellForRowAt is called.



Your best bet would be to use cells for self-calibration. ( https://www.raywenderlich.com/129059/self-sizing-table-view-cells ). Another option is to keep the size of the cells as part of your model and access them here.

+1


source







All Articles