如何用RxSwift去写TableView呢

直接上代码好了-。-,引入了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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,951评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,387评论 25 708
  • 昨晚约写“人生若只如初见”。 人生“若只”,但无“若只”。珍惜生活得到惬意宁静,珍惜工作得到好运眷顾,珍惜朋友得到...
    逸之何春雷阅读 2,311评论 27 94
  • 林苑在一家小公司做财务工作,最近正值年末,公司进行年度的财务清算,林苑每天都要加班到很晚,回到家里往往夜已深了。 ...
    承祈阅读 216评论 0 0
  • 学院召开工程教育专业认证工作启动会 作者:张学敏时间:2018-04-17 (计算机与通信工程学院新闻网) 为确保...
    阿佛11111阅读 146评论 0 0