2016年4月28日木曜日

[RxSwift] SectionありのDataSourceを生成する

本家のサンプルにも記載されている通り、RxDataSourcesを使用する方法があります。
https://github.com/ReactiveX/RxSwift/tree/master/RxExample/RxDataSources

RxDataSources:
https://github.com/RxSwiftCommunity/RxDataSources

Podfileに記載するなりしてインストールしてください。

SectionありのdataSourceを生成する

RxTableViewSectionedReloadDataSourceを使用します。SectionModelでSectionに表示するelementを指定します。

  1. let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>()
  2. let items = Observable.just([
  3. SectionModel(model: "First section", items: [
  4. "aaaa",
  5. "bbbb",
  6. ]),
  7. SectionModel(model: "Second section", items: [
  8. "cccc",
  9. "dddd",
  10. ])
  11. ])


セルの生成

以下のように、indexPathとelementが引数に入っているのでコールバック内でセルを生成する。
  1. dataSource.configureCell = { (_, tableView, indexPath, element) in
  2. let cell = tv.dequeueReusableCellWithIdentifier("Cell")!
  3. cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
  4. return cell
  5. }


データとTablewViewをBindする

  1. items
  2. .bindTo(tableView.rx_itemsWithDataSource(dataSource))
  3. .addDisposableTo(disposeBag)


ヘッダーのカスタマイズ

UITableViewDelegateで処理する必要があります。
以下のように、ヘッダー用のViewとHightを返すモジュールを実装します。
  1. func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  2. let view = UITableViewHeaderFooterView()
  3. view.textLabel?.text = dataSource.sectionAtIndex(section).model ?? ""
  4. return view
  5. }
  6. func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  7. return 44
  8. }

0 件のコメント:

コメントを投稿