RxSwift学习:RxCocoa基础(二)

1,992 阅读5分钟

RxSwift学习:RxCocoa基础(一)

UITableView

单个分区的表格

var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView = UITableView(frame: view.bounds, style: .plain)

    // 注册cell
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid")
    view.addSubview(tableView)

    // 初始化数据
    let items = Observable.just([
        "Swift",
        "Objective-C",
        "JavaScript",
        "Python",
        "Go"
        ])

    // 设置 tableView 数据 (原理是对 cellForRow 的封装)
    items.bind(to: tableView.rx.items) { tableView, row, element in
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellid")!
        cell.textLabel?.text = "\(row): \(element)"
        return cell
    }.disposed(by: disposeBag)
}

单元格选中事件响应

// 设置 tableView 数据 (原理是对 cellForRow 的封装)
items.bind(to: tableView.rx.items) { tableView, row, element in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid")!
    cell.textLabel?.text = "\(row): \(element)"
    return cell
}.disposed(by: disposeBag)

// 获取选中项的索引
tableView.rx.itemSelected.subscribe(onNext: { indexPath in
    print("选中项的indexPath为: \(indexPath)")
}).disposed(by: disposeBag)

// 获取选中项的内容
tableView.rx.modelSelected(String.self).subscribe(onNext: { item in
    print("选中项的标题为: \(item)")
}).disposed(by: disposeBag)

// 获取选中项的索引和内容
Observable.zip(tableView.rx.itemSelected, tableView.rx.modelSelected(String.self)).bind { [weak self] indexPath, item in
    print("~选中项的indexPath为: \(indexPath)")
    print("~选中项的标题为: \(item)")
}.disposed(by: disposeBag)

单元格取消选中事件响应

// 获取被取消选中项的索引
tableView.rx.itemDeselected.subscribe(onNext: { [weak self] indexPath in
    print("被取消选中项的indexPath为: \(indexPath)")
}).disposed(by: disposeBag)

// 获取被取消选中项的内容
tableView.rx.modelDeselected(String.self).subscribe(onNext: { item in
    print("被取消选中项的标题为: \(item)")
}).disposed(by: disposeBag)

// 获取选中项的索引和内容
Observable.zip(tableView.rx.itemSelected, tableView.rx.modelDeselected(String.self)).bind { [weak self] indexPath, item in
    print("~被取消选中项的indexPath为: \(indexPath)")
    print("~被取消选中项的标题为: \(item)")
}.disposed(by: disposeBag)

单元格删除事件响应

// 打开 cell 的编辑功能
tableView.setEditing(true, animated: true)
// 获取删除项的索引
tableView.rx.itemDeleted.subscribe(onNext: { indexPath in
    print("删除项的indexPath: \(indexPath)")
}).disposed(by: disposeBag)

tableView.rx.modelDeleted(String.self).subscribe(onNext: { item in
    print("删除项的item: \(item)")
}).disposed(by: disposeBag)

// 删除项的索引和内容
Observable.zip(tableView.rx.itemDeleted, tableView.rx.modelDeleted(String.self)).bind { indexPath, item in
    print("~删除项的indexPath: \(indexPath)")
    print("~删除项的item: \(item)")
}.disposed(by: disposeBag)

单元格移动事件响应

// 单元格移动事件响应
tableView.setEditing(true, animated: true)
tableView.rx.itemMoved.subscribe(onNext: { sourceIndexPath, destinationIndexPath in
     print("移动项原来的的indexPath: \(sourceIndexPath)")
     print("移动项现在的的indexPath: \(destinationIndexPath)")
}).disposed(by: disposeBag)

// 获取插入项的索引
tableView.rx.itemInserted.subscribe(onNext: { [weak self] indexPath in
    print("插入项的indexPath为:\(indexPath)")
}).disposed(by: disposeBag)

// 获取点击的尾部图标的索引
tableView.rx.itemAccessoryButtonTapped.subscribe(onNext: { [weak self] indexPath in
    print("尾部项的indexPath为:\(indexPath)")
}).disposed(by: disposeBag)

单元格插入事件响应

// 单元格将要显示出来的事件响应
tableView.rx.willDisplayCell.subscribe(onNext: { cell, indexPath in
    print("将要显示的indexPath为:\(indexPath)")
    print("将要显示的cell为:\(indexPath)")
}).disposed(by: disposeBag)

设置代理

// 设置代理
tableView.rx.setDelegate(self).disposed(by: disposeBag)

实现代理方法

// MARK: - UITableViewDelegate
extension RxDataSourcesWithHeaderController: UITableViewDelegate {
    // 设置单元格高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    // 设置分区头的高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    // 是分区头部视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        /// ...
        return headerView
    }
}

UITableView + RxDataSources

RxDataSources 介绍

RxDataSources Github 地址: RxDataSources

官方介绍:

UITableView and UICollectionView Data Sources for RxSwift (sections, animated updates, editing ...)

特点:

  1. RxDataSource 的本质就是使用 RxSwiftUITableViewUICollectionView 的数据源做了一层包装。使用它可以大大减少我们的工作量

  2. RxDataSources 是以 section 来做为数据结构的。所以不管我们的 tableView 是单分区还是多分区,在使用 RxDataSources 的过程中,都需要返回一个 section 的数组

安装

  • CocoaPods

Podfile

pod 'RxDataSources', '~> 3.0'
  • Carthage

Cartfile

github "RxSwiftCommunity/RxDataSources" ~> 3.0

单分区 TableView

方式一:使用自带的Section

// 创建表格
tableView = UITableView(frame: view.bounds, style: .plain)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)

// 初始化数据
let items = Observable.just([
    SectionModel(model: "",
                 items: ["UILabel的用法",
                         "UIButton的用法",
                         "UITextField的用法"])
    ])

// 创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>(configureCell: {
    (dataSource, tableView, indexPath, element) -> UITableViewCell in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
    cell.textLabel?.text = "\(indexPath.row): \(element)"
    return cell
})

// 数据绑定
items.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

方式二:使用自定义的Section

自定义 SectionModel

struct XMSessionModel {
    var header: String
    var items: [Item]
}

extension XMSessionModel: AnimatableSectionModelType {
    
    typealias Item = String
    
    var identity: String {
        return header
    }
    
    init(original: XMSessionModel, items: [Item]) {
        self = original
        self.items = items
    }
}
// 创建表格
tableView = UITableView(frame: view.bounds, style: .plain)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)

// 初始化数据
let sections = Observable.just([
    XMSessionModel(header: "",
                   items: ["UILabel的用法",
                           "UIButton的用法",
                           "UITextField的用法"])
    ])

// 创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<XMSessionModel>( configureCell: {
    (dataSource, tableView, indexPath, item) -> UITableViewCell in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") ?? UITableViewCell(style: .default, reuseIdentifier: "cellID")
    cell.textLabel?.text = "\(indexPath.row): \(item)"
    return cell
})

// 数据绑定
sections.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

多分区的 TableView

方式一:使用自带的Section

// 创建表格
tableView = UITableView(frame: view.bounds, style: .plain)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)

// 初始化数据
let items = Observable.just([
    SectionModel(model: "基本控件",
                   items: ["UILabel的用法",
                           "UIButton的用法",
                           "UITextField的用法"]),
    SectionModel(model: "高级i控件",
                   items: ["UITableView的用法",
                           "UICollectionView的用法"])
    ])

// 创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>( configureCell: {
    (dataSource, tableView, indexPath, element) -> UITableViewCell in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
    cell.textLabel?.text = "\(indexPath.row): \(element)"
    return cell
})

// 设置分区头标题
dataSource.titleForHeaderInSection = { dataSource, index in
    return dataSource.sectionModels[index].model
}

// 设置分区尾部标题
dataSource.titleForFooterInSection = { dataSource, index in
    return "footer"
}

// 数据绑定
items.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

方式二:使用自定义的Section

XMSessionModel 请参考上面的结构

// 创建表格
tableView = UITableView(frame: view.bounds, style: .plain)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)

// 初始化数据
let items = Observable.just([
    XMSessionModel(header: "基本控件",
                   items: ["UILabel的用法",
                           "UIButton的用法",
                           "UITextField的用法"]),
    XMSessionModel(header: "高级i控件",
                   items: ["UITableView的用法",
                           "UICollectionView的用法"])
    ])

// 创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<XMSessionModel>( configureCell: {
    (dataSource, tableView, indexPath, element) -> UITableViewCell in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
    cell.textLabel?.text = "\(indexPath.row): \(element)"
    return cell
})

// 设置分区头标题
dataSource.titleForHeaderInSection = { dataSource, index in
    return dataSource.sectionModels[index].header
}

// 设置分区尾部标题
dataSource.titleForFooterInSection = { dataSource, index in
    return "footer"
}

// 数据绑定
items.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

UITableView + Refresh

TableView 通常要和 Refresh功能结合使用, Refresh 大都从网络获取数据然后进行刷新

下文模拟数据请求和表格刷新

数据获取, 返回列表数据

/// 获取数据
func getRandomResult() -> Observable<[SectionModel<String, Int>]> {
    let items = (0..<5).map { _ in Int(arc4random()) }
    let observable = Observable.just([SectionModel(model: "S", items: items)])
    return observable.delay(2, scheduler: MainScheduler.instance) // 模拟网络请求 延迟2秒钟
}

创建表格并绑定数据

/// 设置导航栏右侧按钮为刷新
let refreshButton = UIBarButtonItem()
refreshButton.title = "刷新"
self.navigationItem.rightBarButtonItem = refreshButton

// 创建表格
tableView = UITableView(frame: view.bounds, style: .plain)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
view.addSubview(tableView)

// 初始化数据
let randomResult = refreshButton.rx.tap.asObservable()
    .throttle(1, scheduler: MainScheduler.instance) // 在主线程中操作, 若1秒钟多次改变, 取最后一次
    .startWith(()) // 加这个是为了一开始就能自动请求一次数据
    .flatMapLatest(getRandomResult) // 连续请求时只取最后一次数据
    .share(replay: 1)


// 创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Int>>( configureCell: {
    (dataSource, tableView, indexPath, element) -> UITableViewCell in
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")!
    cell.textLabel?.text = "条目\(indexPath.row): \(element)"
    return cell
})

// 数据绑定
randomResult.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

停止数据请求

使用 takeUntil 来停止数据请求

let cancelButton = UIBarButtonItem()
cancelButton.title = "取消"
self.navigationItem.leftBarButtonItem = cancelButton

`
`
`
// 初始化数据
let randomResult = refreshButton.rx.tap.asObservable()
    .throttle(1, scheduler: MainScheduler.instance) // 在主线程中操作, 若1秒钟多次改变, 取最后一次
    .startWith(()) // 加这个是为了一开始就能自动请求一次数据
    .flatMapLatest({
    // 核心代码
    self.getRandomResult().takeUntil(self.cancelButton.rx.tap) }) // 停止数据请求
    .share(replay: 1)
    
`
`
`

收录自|地址

Swift书籍资料下载:下载地址