RxSwift 深入浅出(六)RxDataSources

RxSwift 这个框架看我就够了,这一篇我重点介绍RxDataSources在实际开发中的运用,RxDataSourcestableview的分组是特别爽的。搞RxSwift,我是认真的

RxSwift 宝图镇博,咔咔点赞~~~~

Rxswift
import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class RxSwiftTableVC: UIViewController {
    
    var myTableView:UITableView!
    let reuserId = "cell"
    let disposeB = DisposeBag()
    let datas = GithubData()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "RxSwift进阶";
        self.view.backgroundColor = UIColor.white
        self.myTableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.plain)
        self.view.addSubview(self.myTableView)
        self.myTableView.register(SectionTableCell.self, forCellReuseIdentifier: reuserId)
        
        let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, SectionDataModel>>(
            configureCell: { [weak self](ds, tb, index, model) -> SectionTableCell in
            let cell = tb.dequeueReusableCell(withIdentifier: (self?.reuserId)!, for: index) as? SectionTableCell

           // cell?.detailTextLabel?.backgroundColor = UIColor.orange
            cell?.imageView?.image = model.image
            cell?.textLabel?.text = model.name
            cell?.detailTextLabel?.text = model.gitHubID
            return cell!
        },
            titleForHeaderInSection:{ds, index in
                return ds.sectionModels[index].model
        })

        datas.githubData.asDriver(onErrorJustReturn: [])
            .drive(myTableView.rx.items(dataSource: dataSource))
            .disposed(by:disposeB)

        myTableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
               self?.navigationController?.pushViewController(RxSearchVC(), animated: true)
            })
            .disposed(by:disposeB)

//        myTableView.delegate = self
        myTableView.rx.setDelegate(self).disposed(by: disposeB)
    }
   
}


class SectionTableCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: reuseIdentifier)
        print(#function)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


struct SectionDataModel {

    let name: String
    let gitHubID: String
    var image: UIImage?
    
    init(name: String, gitHubID: String) {
        self.name = name
        self.gitHubID = gitHubID
        image = UIImage(named: gitHubID)
    }
}

extension SectionDataModel:IdentifiableType{
    typealias Identity = String
    var identity:Identity {return gitHubID}
}

class GithubData {
    let githubData = Observable.just([
        SectionModel(model: "A", items: [
            SectionDataModel(name: "Alex V Bush", gitHubID: "alexvbush"),
            SectionDataModel(name: "Andrew Breckenridge", gitHubID: "AndrewSB"),
            SectionDataModel(name: "Anton Efimenko", gitHubID: "reloni"),
            SectionDataModel(name: "Ash Furrow", gitHubID: "ashfurrow"),
            ]),
        SectionModel(model: "B", items: [
            SectionDataModel(name: "Ben Emdon", gitHubID: "BenEmdon"),
            SectionDataModel(name: "Bob Spryn", gitHubID: "sprynmr"),
            ]),
        SectionModel(model: "C", items: [
            SectionDataModel(name: "Carlos García", gitHubID: "carlosypunto"),
            SectionDataModel(name: "Cezary Kopacz", gitHubID: "CezaryKopacz"),
            SectionDataModel(name: "Chris Jimenez", gitHubID: "PiXeL16"),
            SectionDataModel(name: "Christian Tietze", gitHubID: "DivineDominion"),
            ]),
        SectionModel(model: "D", items: [
            SectionDataModel(name: "だいちろ", gitHubID: "mokumoku"),
            SectionDataModel(name: "David Alejandro", gitHubID: "davidlondono"),
            SectionDataModel(name: "David Paschich", gitHubID: "dpassage"),
            ]),
        SectionModel(model: "E", items: [
            SectionDataModel(name: "Esteban Torres", gitHubID: "esttorhe"),
            SectionDataModel(name: "Evgeny Aleksandrov", gitHubID: "ealeksandrov"),
            ]),
        SectionModel(model: "F", items: [
            SectionDataModel(name: "Florent Pillet", gitHubID: "fpillet"),
            SectionDataModel(name: "Francis Chong", gitHubID: "siuying"),
            ]),
        SectionModel(model: "G", items: [
            SectionDataModel(name: "Giorgos Tsiapaliokas", gitHubID: "terietor"),
            SectionDataModel(name: "Guy Kahlon", gitHubID: "GuyKahlon"),
            SectionDataModel(name: "Gwendal Roué", gitHubID: "groue"),
            ]),
        SectionModel(model: "H", items: [
            SectionDataModel(name: "Hiroshi Kimura", gitHubID: "muukii"),
            ]),
        SectionModel(model: "I", items: [
            SectionDataModel(name: "Ivan Bruel", gitHubID: "ivanbruel"),
            ]),
        SectionModel(model: "J", items: [
            SectionDataModel(name: "Jeon Suyeol", gitHubID: "devxoul"),
            SectionDataModel(name: "Jérôme Alves", gitHubID: "jegnux"),
            SectionDataModel(name: "Jesse Farless", gitHubID: "solidcell"),
            SectionDataModel(name: "Junior B.", gitHubID: "bontoJR"),
            SectionDataModel(name: "Justin Swart", gitHubID: "justinswart"),
            ]),
        SectionModel(model: "K", items: [
            SectionDataModel(name: "Karlo", gitHubID: "floskel"),
            SectionDataModel(name: "Krunoslav Zaher", gitHubID: "kzaher"),
            ]),
        SectionModel(model: "L", items: [
            SectionDataModel(name: "Laurin Brandner", gitHubID: "lbrndnr"),
            SectionDataModel(name: "Lee Sun-Hyoup", gitHubID: "kciter"),
            SectionDataModel(name: "Leo Picado", gitHubID: "leopic"),
            SectionDataModel(name: "Libor Huspenina", gitHubID: "libec"),
            SectionDataModel(name: "Lukas Lipka", gitHubID: "lipka"),
            SectionDataModel(name: "Łukasz Mróz", gitHubID: "sunshinejr"),
            ]),
        SectionModel(model: "M", items: [
            SectionDataModel(name: "Marin Todorov", gitHubID: "icanzilb"),
            SectionDataModel(name: "Maurício Hanika", gitHubID: "mAu888"),
            SectionDataModel(name: "Maximilian Alexander", gitHubID: "mbalex99"),
            ]),
        SectionModel(model: "N", items: [
            SectionDataModel(name: "Nathan Kot", gitHubID: "nathankot"),
            ]),
        SectionModel(model: "O", items: [
            SectionDataModel(name: "Orakaro", gitHubID: "DTVD"),
            SectionDataModel(name: "Orta", gitHubID: "orta"),
            ]),
        SectionModel(model: "P", items: [
            SectionDataModel(name: "Paweł Urbanek", gitHubID: "pawurb"),
            SectionDataModel(name: "Pedro Piñera Buendía", gitHubID: "pepibumur"),
            SectionDataModel(name: "PG Herveou", gitHubID: "pgherveou"),
            ]),
        SectionModel(model: "R", items: [
            SectionDataModel(name: "Rui Costa", gitHubID: "ruipfcosta"),
            SectionDataModel(name: "Ryo Fukuda", gitHubID: "yuzushioh"),
            ]),
        SectionModel(model: "S", items: [
            SectionDataModel(name: "Scott Gardner", gitHubID: "scotteg"),
            SectionDataModel(name: "Scott Hoyt", gitHubID: "scottrhoyt"),
            SectionDataModel(name: "Sendy Halim", gitHubID: "sendyhalim"),
            SectionDataModel(name: "Serg Dort", gitHubID: "sergdort"),
            SectionDataModel(name: "Shai Mishali", gitHubID: "freak4pc"),
            SectionDataModel(name: "Shams Ahmed", gitHubID: "shams-ahmed"),
            SectionDataModel(name: "Shenghan Chen", gitHubID: "zzdjk6"),
            SectionDataModel(name: "Shunki Tan", gitHubID: "milkit"),
            SectionDataModel(name: "Spiros Gerokostas", gitHubID: "sger"),
            SectionDataModel(name: "Stefano Mondino", gitHubID: "stefanomondino"),
            ]),
        SectionModel(model: "T", items: [
            SectionDataModel(name: "Thane Gill", gitHubID: "thanegill"),
            SectionDataModel(name: "Thomas Duplomb", gitHubID: "tomahh"),
            SectionDataModel(name: "Tomasz Pikć", gitHubID: "pikciu"),
            SectionDataModel(name: "Tony Arnold", gitHubID: "tonyarnold"),
            SectionDataModel(name: "Torsten Curdt", gitHubID: "tcurdt"),
            ]),
        SectionModel(model: "V", items: [
            SectionDataModel(name: "Vladimir Burdukov", gitHubID: "chipp"),
            ]),
        SectionModel(model: "W", items: [
            SectionDataModel(name: "Wolfgang Lutz", gitHubID: "Lutzifer"),
            ]),
        SectionModel(model: "X", items: [
            SectionDataModel(name: "xixi197 Nova", gitHubID: "xixi197"),
            ]),
        SectionModel(model: "Y", items: [
            SectionDataModel(name: "Yongha Yoo", gitHubID: "inkyfox"),
            SectionDataModel(name: "Yosuke Ishikawa", gitHubID: "ishkawa"),
            SectionDataModel(name: "Yury Korolev", gitHubID: "yury"),
            ]),
        ])
}

extension RxSwiftTableVC:UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(arc4random_uniform(60)+32)
    }
}

RxDataSources的分组效果是非常爽的,我们现在看一下它的封装

    public typealias ConfigureCell = (TableViewSectionedDataSource<S>, UITableView, IndexPath, I) -> UITableViewCell
    public typealias TitleForHeaderInSection = (TableViewSectionedDataSource<S>, Int) -> String?
    public typealias TitleForFooterInSection = (TableViewSectionedDataSource<S>, Int) -> String?
    public typealias CanEditRowAtIndexPath = (TableViewSectionedDataSource<S>, IndexPath) -> Bool
    public typealias CanMoveRowAtIndexPath = (TableViewSectionedDataSource<S>, IndexPath) -> Bool

定义了几个闭包,也是我们在分组中经常要用到的

 public init(
                configureCell: @escaping ConfigureCell,
                titleForHeaderInSection: @escaping  TitleForHeaderInSection = { _, _ in nil },
                titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil },
                canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false },
                canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false },
                sectionIndexTitles: @escaping SectionIndexTitles = { _ in nil },
                sectionForSectionIndexTitle: @escaping SectionForSectionIndexTitle = { _, _, index in index }
            ) {
            self.configureCell = configureCell
            self.titleForHeaderInSection = titleForHeaderInSection
            self.titleForFooterInSection = titleForFooterInSection
            self.canEditRowAtIndexPath = canEditRowAtIndexPath
            self.canMoveRowAtIndexPath = canMoveRowAtIndexPath
            self.sectionIndexTitles = sectionIndexTitles
            self.sectionForSectionIndexTitle = sectionForSectionIndexTitle
        }

在初始化的时候就对上面的闭包进行了默认值处理(除了configureCell),这也很好解释,因为对于分组来说,其他那些头,尾都是非必须的,cell的逻辑才是必须要的,这也就促成了它封装两个configureCell的方法的原因

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容

  • RxSwift 这个框架看我就够了,这一篇我重点介绍RxSwift在实际开发中的运用。搞RxSwift,我是认真的...
    Cooci_和谐学习_不急不躁阅读 4,357评论 3 6
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,574评论 25 707
  • 秀发飞舞,眸闭颌扬 感应到了你内心的彷徨 仿佛内心世界正在流浪 什么让曾经的快乐天使 变得黯伤 什么让七彩梦中的浅...
    若天无云_CF阅读 3,941评论 118 135
  • 工作已经一个月多一点了,与以往不同的是,多了很多很多独处的时间,会多一些自己的思考,积极主动果然是有用的,它好歹,...
    小火棍阅读 158评论 0 0