如果有人感兴趣,这是我的实现。我有一个包含游戏列表的应用程序。根据游戏是否完成或仍在进行中,我使用不同的单元格。这是我的代码:
在 ViewModel 中,我有一个游戏列表,将它们分成已完成/正在进行的游戏并将它们映射到 SectionModel
let gameSections = PublishSubject<[SectionModel<String, Game>]>()
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Game>>()
...
self.games.asObservable().map {[weak self] (games: [Game]) -> [SectionModel<String, Game>] in
guard let safeSelf = self else {return []}
safeSelf.ongoingGames = games.filter({$0.status != .finished})
safeSelf.finishedGames = games.filter({$0.status == .finished})
return [SectionModel(model: "Ongoing", items: safeSelf.ongoingGames), SectionModel(model: "Finished", items: safeSelf.finishedGames)]
}.bindTo(gameSections).addDisposableTo(bag)
然后在 ViewController 中,我将我的部分绑定到我的 tableview,并像这样使用不同的单元格。请注意,我可以使用 indexPath 来获取正确的单元格而不是状态。
vm.gameSections.asObservable().bindTo(tableView.rx.items(dataSource: vm.dataSource)).addDisposableTo(bag)
vm.dataSource.configureCell = {[weak self] (datasource, tableview, indexpath, item) -> UITableViewCell in
if item.status == .finished {
let cell = tableview.dequeueReusableCell(withIdentifier: "FinishedGameCell", for: indexpath) as! FinishedGameCell
cell.nameLabel.text = item.opponent.shortName
return cell
} else {
let cell = tableview.dequeueReusableCell(withIdentifier: "OnGoingGameCell", for: indexpath) as! OnGoingGameCell
cell.titleLabel.text = item.opponent.shortName
return cell
}
}