具有多个自定义单元格类型的RxSwift表视图

edz*_*o27 16 uitableview ios swift swift2 rx-swift

我不知道有什么代码示例RxSwift可以在一个表视图中使用多个自定义单元格.例如,我有两个部分,第一部分有10个带有类型CellWithImage标识符的单元格,第二部分有10个带有类型CellWithVideo标识符的单元格.

我创建的所有tuts和代码示例都只使用一种单元格类型,例如RxSwiftTableViewExample

谢谢你的帮助

小智 16

您可以在没有 RxDatasource 的情况下设置多个自定义单元格。

    //Register Cells as you want
    tableView.register(CustomRxTableViewCell.self, forCellReuseIdentifier: "Cell")
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicCell")



    ViewModel.data.bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

        if row == 0 {
            let cell = tv.dequeueReusableCell(withIdentifier: "BasicCell", for: IndexPath.init(row: row, section: 0))

            cell.textLabel?.text = item.birthday
            return cell
        }else{
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath.init(row: row, section: 0)) as! CustomRxTableViewCell
            cell.titleLb.text = item.name
            return cell
        }

    }.disposed(by: disposeBag)
Run Code Online (Sandbox Code Playgroud)


edz*_*o27 10

我用RxSwiftDataSources管理它,

它允许您使用具有多个部分的自定义单元格. 我已经使用此代码寻求帮助

  • 你可以分享一下你如何实现这个的代码吗? (5认同)

str*_*eem 5

如果有人感兴趣,这是我的实现。我有一个包含游戏列表的应用程序。根据游戏是完成还是仍在进行中,我使用不同的单元格。这是我的代码:

在 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)
Run Code Online (Sandbox Code Playgroud)

然后在 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
    }
}
Run Code Online (Sandbox Code Playgroud)