我做了一个
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。 我不知道该怎么办。
针对这种情况有以下几种方法:
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 {
...
}
}
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)