2017-03-25 7 views
3

私はUITableViewを持つビューコントローラを持っています。テーブルデータはRxSwiftを使用して移入さ:RxSwift + UITableViewCellでheightForRowAtのセルオブジェクトを取得する方法

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() 
} 
+0

モデルに必要なパラメータを追加し、データソース配列から情報を取得します。 – vadian

+0

私は、セルの高さを計算する関数をセルクラスに持っています。私は複数のプロトタイプのセルを持っているので、私はそれを統一したい。したがって、その機能をビジネスロジックの一部であるモデルに組み込むことは賢明ではありません。 – Gasim

+0

私の編集内容を確認してください。 – Gasim

答えて

1

heightForRowAtがcellForRowAtが呼び出される前に、特定のindexPath に呼び出されるためtableView.cellForRow(at: indexPath)リターンがtableView(_: heightForRowAt:)にnilをコール。

セルフサイジングセルを使用するのが最善の方法です。 (https://www.raywenderlich.com/129059/self-sizing-table-view-cells)。もう1つの選択肢は、セルのサイズをモデルの一部として保持し、ここにアクセスすることです。

関連する問題