直接上代码好了-。-,引入了RxDataSources, 注意看注释
import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxDataSources
import Differentiator //这个不添加也可以,只是方便查看SectionModel代码
class GameListController :UIViewController{
private var tableView: UITableView!
private let disposeBag = DisposeBag()
var viewModel:GameListViewModel!
/*
SectionModel 的部分源码
public struct SectionModel<Section, ItemType> {
public var model: Section
public var items: [Item]
public init(model: Section, items: [Item]) {
self.model = model
self.items = items
}
}
model 是用来让你存东西的,不用也行,我这里设置为String类型,并传入""
ItemType 是Cell的模型类型
*/
private let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, MatchViewModel>>(configureCell:{ ds, tv, ip, model in
let cell = tv.dequeueReusableCell(withIdentifier: "MatchCell", for: ip)
model.configure(tableView: tv, cell: cell, indexPath: ip)
return cell
})
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupBindings()
}
private func setupUI() {
tableView = UITableView(frame: CGRect(), style: .plain)
view.addSubview(tableView)
tableView.snp.makeConstraints{ maker in
maker.edges.equalTo(view.snp.edges)
}
tableView.register(MatchCell.self, forCellReuseIdentifier: "MatchCell")
tableView.rx.setDelegate(self).disposed(by: disposeBag)
}
private func setupBindings(){
viewModel.matchViewModels
.observeOn(MainScheduler.instance)
.do(onNext: { [weak self] _ in
self?.tableView.mj_header.endRefreshing()})
.filter{ !$0.isEmpty }
.map { [ SectionModel(model: "", items: $0) ] }
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
@objc func headerRefresh(){
viewModel.reload.onNext(Void())
}
}
extension GameListController: UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let model = try! dataSource.model(at: indexPath) as! CellModel
return model.heightForCell
}
}
如果要创建自己的SectionModel,可以去看RxDataSources