如何使用RxSwift根据数据数量绘制UICollectionView单元格

问题描述 投票:0回答:1

我做了一个

var sample = Public Subject <[]>()
,我将用它绘制一个元音视图。 如果
samples
的数量为0,我想绘制一个集合视图单元格,如果超过1个,我想根据
samples
的数量来绘制。

self.viewModel.sample
    .bind(to: collectionView.rx.items(
        cellIdentifier: "cell",
        cellType: Cell.self
    )) { index, item , cell in
        //
    }
    .disposed(by: disposeBag)

我只知道如何按照上面的方法实现。 我该怎么办?

这是我第一次使用 RxSwift。 我不知道该怎么办。

swift uicollectionview uikit rx-swift
1个回答
0
投票

针对这种情况有以下几种方法:

  1. 处理数据:您可以在
    viewModel.sample
    内定义多种类型,即占位符或普通。如果
    viewModel.sample
    为空,您只需附加一个占位符,然后根据
    type
    切换单元格的 UI。
enum DataType {
  case placeholder
  case normal
}

struct Sample {
  let type: DataType
  //Other stuff
}

viewModel.sample.bind... { index, item , cell in
  if item.type == .placeholder {
    ...
  else {
    ...
  }
}

  1. 或者使用
    RxTableViewDataSourceType
    返回数据源样式。
final class SampleDataSource: NSObject, UITableViewDataSource, RxTableViewDataSourceType {
  private var models: [Sample] = []
  
  func tableView(_ tableView: UITableView, observedEvent: Event<[Sample]>) {
    switch observedEvent {
      case .next(let models):
        self.models = models
        tableView.reloadData()
      default: 
        break
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if models.isEmpty {
      let placeholerCell = ...
    } else {
      let cell = ...
    }
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    models.isEmpty ? 1 : models.count
  }
}

然后将

viewModel.sample
绑定到此
SampleDataSource
:

viewModel.sample
  .bind(to: tableView.rx.items(dataSource: SampleDataSource()))
  .disposed(by: disposeBag)
© www.soinside.com 2019 - 2024. All rights reserved.