本文讲解的是RxSwift UITableView的
分组(一个或多个section)
样式的实现
1、工程依赖库
podfile文件添加依赖库
pod 'RxSwift'
pod 'RxCocoa'
pod 'RxDataSources'
2、ViewController中添加如下代码
//
// HomeViewController.swift
// RxSwiftDemo
//
// Created by wsj_2012 on 2020/8/7.
// Copyright © 2020 wsj_2012. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class HomeViewController: UIViewController {
let disposeBag = DisposeBag.init()
let homeModel = HomeModel()
lazy var tableView: UITableView = {
let tableview = UITableView.init(frame: self.view.bounds,style: .plain)
tableview.tableFooterView = UIView()
tableview.register(RowViewCell.classForCoder(), forCellReuseIdentifier: "resuseID")
tableview.rowHeight = 100
return tableview
}()
// <SectionModel<String, RowModel.Row> 对象类型RowModel.Row须与Model中BehaviorRelay实例中items数组存储的数据对象类型一致
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, RowModel.Row>>(
configureCell: { (_, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "resuseID") as? RowViewCell
cell?.textLabel?.text = "\(element.title!) @ row \(indexPath.row)"
return cell ?? RowViewCell(style: .default, reuseIdentifier: "resuseID")
},
titleForHeaderInSection: { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
)
override func viewDidLoad() {
super.viewDidLoad()
title = "新闻"
view.backgroundColor = .white
// Do any additional setup after loading the view.
setupSubViews()
bindViewModel()
updateData()
}
func setupSubViews() {
view.addSubview(tableView)
}
func bindViewModel() -> Void {
homeModel.groupItems.bind(to: tableView.rx.items(dataSource: self.dataSource)).disposed(by: disposeBag)
}
func updateData() {
homeModel.updateGroupModels()
}
}
3、ViewController中用到的HomeModel.swift类
//
// HomeModel.swift
// RxSwiftDemo
//
// Created by wsj_2012 on 2020/8/7.
// Copyright © 2020 wsj_2012. All rights reserved.
//
import UIKit
import RxDataSources
import RxRelay
class HomeModel: NSObject {
var groupItems = BehaviorRelay(value: [SectionModel(model: "", items: [RowModel.Row.init()])])
func updateGroupModels() {
var arr: [RowModel.Row] = []
for i in 0...10 {
let m = RowModel.Row(title: "标题\(i)", subTitle: "副标题\(i)")
arr.append(m)
}
groupItems.accept([SectionModel(model: "Section", items: arr)])
}
}
4、ViewController类中的RowViewCell
RowViewCell.swift类自行创建,继承自UITableViewCell
网友评论