复杂UITableview绑定Rx实现
RxCocoa没有实现复杂UITableview数据绑定(如多组数据、cell编辑等),需要自行实现,不过通过对RxCocoa中UITableview单组数据绑定的分析,其实实现思路是一样的。
定义一个SectionModelType
协议来规范整个组的数据:
protocol SectionModelType {
associatedtype Section
associatedtype Item
var model: Section { get }
var items: [Item] { get }
init(model: Section, items: [Item])
}
- 定义了两个关联类型
Section
,Item
表示组数据和组中的行数据 - 定义两个属性
model
,items
存储组数据和组中的行数据
定义一个SectionModelType
类来存储、关联源数据的数据:
class SectionedDataSource<Section: NSObject, SectionModelType>: SectionedViewDataSourceType {
private var _sectionModels: [Section] = []
func setSections(_ sections: [Section]) {
_sectionModels = sections
}
func sectionsCount() -> Int {
return _sectionModels.count
}
func itemsCount(section: Int) -> Int {
return _sectionModels[section].items.count
}
subscript(section: Int) -> Section {
let sectionModel = _sectionModels[section]
return Section(model: sectionModel.model, items: sectionModel.items)
}
subscript(indexPath: IndexPath) -> Section.Item {
return _sectionModels[indexPath.section].items[indexPath.row]
}
// MARK: SectionedViewDataSourceType
func model(at indexPath: IndexPath) throws -> Any { self[indexPath] }
}
- 该类遵守
SectionedViewDataSourceType
协议来规定如何获取数据 - 该类的本质存储组数据数组,并且定义了一些简便的函数来获取数据
定义一个TableViewSectionedDataSource
类继承自SectionedDataSource
,遵守UITableViewDataSource
、RxTableViewDataSourceType协议
:
class TableViewSectionedDataSource<Section: SectionModelType>: SectionedDataSource<Section>, UITableViewDataSource, RxTableViewDataSourceType {
typealias CellForRow = (TableViewSectionedDataSource<Section>, UITableView, IndexPath) -> UITableViewCell
typealias TitleForHeader = (TableViewSectionedDataSource<Section>, UITableView, Int) -> String?
typealias TitleForFooter = (TableViewSectionedDataSource<Section>, UITableView, Int) -> String?
typealias CanEditRow = (TableViewSectionedDataSource<Section>, UITableView, IndexPath) -> Bool
typealias CanMoveRow = (TableViewSectionedDataSource<Section>, UITableView, IndexPath) -> Bool
var cellForRow: CellForRow
var titleForHeader: TitleForHeader
var canEditRow: CanEditRow
var canMoveRow: CanMoveRow
init(cellForRow: @escaping CellForRow, titleForHeader: @escaping TitleForHeader = { _,_,_ in nil }, canEditRow: @escaping CanEditRow = { _,_,_ in false }, canMoveRow: @escaping CanMoveRow = { _,_,_ in false }) {
self.cellForRow = cellForRow
self.titleForHeader = titleForHeader
self.canEditRow = canEditRow
self.canMoveRow = canMoveRow
super.init()
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int { sectionsCount() }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { itemsCount(section: section) }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { cellForRow(self, tableView, indexPath) }
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { titleForHeader(self, tableView, section) }
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { nil }
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { canEditRow(self, tableView, indexPath) }
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { canMoveRow(self, tableView, indexPath) }
// MArK: RxTableViewDataSourceType
typealias Element = [Section]
func tableView(_ tableView: UITableView, observedEvent: Event<TableViewSectionedDataSource<Section>.Element>) {
Binder(self) { (dataSource, element: Element) in
dataSource.setSections(element)
tableView.reloadData()
}.on(observedEvent)
}
}
- 类继承
SectionedDataSource
是达到对原数据的取用 - 遵守
UITableViewDataSource
协议为UITableview
提供数据 - 遵守
RxTableViewDataSourceType
协议实现对UITableview的datasource
代理所需数据存储,并刷新列表 -
cellForRow
、titleForHeader
、canEditRow
、canMoveRow
这几个属性分别存储将原数据转化为UITableViewDataSource
协议所需要数据的闭包,既是行的cell、组头的标题、行能否编辑、行能否移动
多组数据绑定
新建控制器,构建一个UITableview作为属性tableView
。
定义SectionModel
遵守SectionModelType
表示组数据:
struct SectionModel<SectionType, ItemType>: SectionModelType {
typealias Section = SectionType
typealias Item = ItemType
var model: Section
var items: [Item]
init(model: Section, items: [Item]) {
self.model = model
self.items = items
}
}
构建数据序列绑定到tableView
:
let observable = Observable.just([
SectionModel(model: 1, items: Array(1...10)),
SectionModel(model: 2, items: Array(1...10)),
SectionModel(model: 3, items: Array(1...10)),
SectionModel(model: 4, items: Array(1...10)),
SectionModel(model: 5, items: Array(1...10)),
SectionModel(model: 6, items: Array(1...10)),
SectionModel(model: 7, items: Array(1...10)),
SectionModel(model: 8, items: Array(1...10)),
SectionModel(model: 9, items: Array(1...10)),
SectionModel(model: 10, items: Array(1...10))
])
let dataSource = TableViewSectionedDataSource<SectionModel<Int, Int>>(cellForRow: { (dataSource, tableView, indexPath) -> UITableViewCell in
let cell = CommonCell.cellFor(tableView: tableView)
let item = dataSource[indexPath]
cell.textLabel?.text = "我是(\(indexPath.section), \(indexPath.row)), \(item)"
return cell
}, titleForHeader: { "第\($2)组我是\($0[$2].model)" })
observable.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: bag)
可编辑的UITableView绑定
新建一个控制器,构建一个UITableview作为属性tableView。
在导航栏右侧设置编辑item
:
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem?.title = "编辑"
重写控制器的setEditing
函数来编辑UITableview:
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.isEditing = editing
navigationItem.rightBarButtonItem?.title = editing ? "完成" : "编辑"
}
这个示例稍微复杂,数据是从网络获得,首先定义数据模型与网络请求工具:
struct User: CustomStringConvertible {
var firstName: String
var lastName: String
var imageURL: String
var description: String {
return "\(firstName) \(lastName)"
}
}
class UserAPI {
class func getUsers(count: Int) -> Observable<[User]> {
let url = URL(string: "http://api.randomuser.me/?results=\(count)")!
return URLSession.shared.rx.json(url: url).map { (json) -> [User] in
guard let json = json as? [String: AnyObject] else {
fatalError()
}
guard let results = json["results"] as? [[String: AnyObject]] else {
fatalError()
}
return results.map { (info) -> User in
let name = info["name"] as? [String: String]
let picture = info["picture"] as? [String: String]
guard let firstName = name?["first"], let lastName = name?["last"], let imageURL = picture?["large"] else {
fatalError()
}
return User(firstName: firstName, lastName: lastName, imageURL: imageURL)
}
}.share(replay: 1)
}
}
定义枚举EditingTableViewCommand
表示对UITableView
的操作:
enum EditingTableViewCommand {
case addUsers(users: [User], to: IndexPath)
case moveUser(from: IndexPath, to: IndexPath)
case deleteUser(indexPath: IndexPath)
}
定义EditingTabelViewViewModel
处理UI逻辑:
struct EditingTabelViewViewModel {
static let initalSections: [SectionModel<String, User>] = [
SectionModel<String, User>(model: "Favorite Users", items: [
User(firstName: "Super", lastName: "Man", imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg"),
User(firstName: "Wat", lastName: "Man", imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF")]),
SectionModel<String, User>(model: "Normal Users", items: [User]())
]
private let activity = ActivityIndicator()
let sections: Driver<[SectionModel<String, User>]>
let loading: Driver<Bool>
static func excuteCommand(sections: [SectionModel<String, User>], command: EditingTableViewCommand) -> [SectionModel<String, User>] {
var result = sections
switch command {
case let .addUsers(users, to):
result[to.section].items.insert(contentsOf: users, at: to.row)
case let .moveUser(from, to):
let user = sections[from.section].items[from.row]
result[from.section].items.remove(at: from.row)
result[to.section].items.insert(user, at: to.row)
case let .deleteUser(indexPath):
result[indexPath.section].items.remove(at: indexPath.row)
}
return result
}
init(itemDelete: RxCocoa.ControlEvent<IndexPath>, itemMoved: RxCocoa.ControlEvent<RxCocoa.ItemMovedEvent>) {
self.loading = activity.asDriver(onErrorJustReturn: false)
let add = UserAPI.getUsers(count: 30)
.map { EditingTableViewCommand.addUsers(users: $0, to: IndexPath(row: 0, section: 1)) }
.trackActivity(activity)
sections = Observable.deferred {
let delete = itemDelete.map { EditingTableViewCommand.deleteUser(indexPath: $0) }
let move = itemMoved.map(EditingTableViewCommand.moveUser)
return Observable.merge(add, delete, move)
.scan(EditingTabelViewViewModel.initalSections, accumulator: EditingTabelViewViewModel.excuteCommand(sections:command:))
}.startWith(EditingTabelViewViewModel.initalSections)
.asDriver(onErrorJustReturn: EditingTabelViewViewModel.initalSections)
}
}
- 类型属性
initalSections
存储初始数据,私有属性activity
用来记录网络活动状态序列,属性sections
为UITableView数据序列,属性loading
为网络加载状态序列 - 类函数
excuteCommand
根据对UITableview
的操作EditingTableViewCommand
处理数据 - 初始化时用私有属性
activity
转化为Driver
作为loading
属性 - 初始化时使用
UserAPI
类的getUsers
类型函数得到一个获取数据的序列,然后使用map
操作符转化为EditingTableViewCommand
操作的序列记为add
- 初始化时将参数删除和移动
UITableView
行的序列转化为EditingTableViewCommand
操作的序列分别记为delete
、move
- 初始化时将
add
、delete
、move
这三个序列使用merge
操作符合并为一个序列,然后使用scan
操作符扫描序列将类型属性initalSections
作为初始数据、类型函数excuteCommand
作为转换函数处理成一个元素为[SectionModel<String, User>]
类型的序列,最后再使用startWith
和asDriver
操作符设置初始元素并转换为Driver
类型的序列
UITableVIew
数据复杂绑定实现方式并没有变化跟简单绑定是一样的,无非就是在对UITableview
进行操作时相应处理需要绑定到UITableview
上的原数据如EditingTabelViewViewModel
中的excuteCommand
函数,并且在构建TableViewSectionedDataSource
时多提供一些canEditRow
,canMoveRow
等闭包为UITableViewDataSource
协议中定义的函数提供数据支持。
在控制器中构建一个懒加载属性dataSource
提供Cell
生成、组头部标题、是否可以编辑、是否可以移动等闭包:
lazy var dataSource: TableViewSectionedDataSource<SectionModel<String, User>> = { TableViewSectionedDataSource<SectionModel<String, User>>(cellForRow: { ds, tv, indexPath in
let cell = CommonCell.cellFor(tableView: tv)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.textLabel?.text = ds[indexPath].firstName + " " + ds[indexPath].lastName
return cell
}, titleForHeader: { "\($0[$2].model)>\($0[$2].items)" }, canEditRow: { _,_,_ in true }, canMoveRow: { _,_,_ in true }) }()
扩展Reactive
用来绑定加载动画:
extension Reactive where Base: UIViewController & NVActivityIndicatorViewable {
var animating: Binder<Bool> {
return Binder(base) { (t, v) in
if v != t.isAnimating {
if v {
t.startAnimating()
} else {
t.stopAnimating()
}
}
UIApplication.shared.isNetworkActivityIndicatorVisible = v
}
}
}
最后构建EditingTabelViewViewModel
,进行数据绑定:
let viewModel: EditingTabelViewViewModel = EditingTabelViewViewModel(itemDelete: tableView.rx.itemDeleted, itemMoved: tableView.rx.itemMoved)
viewModel.loading
.drive(self.rx.animating)
.disposed(by: bag)
viewModel.sections
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: bag)
tableView.rx
.modelSelected(User.self)
.subscribe(onNext: { [weak self] (user) in
let viewController = UIStoryboard(name: "EditingTableView", bundle: Bundle.main).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
viewController.user = user
self?.navigationController?.pushViewController(viewController, animated: true)
}).disposed(by: bag)
tableView.rx
.itemSelected
.subscribe(onNext: { [weak self] in self!.tableView.deselectRow(at: $0, animated: true) })
.disposed(by: bag)
扩展
参考UIPickerView的Rx实现,其实还可以定义TableViewSectionedDataSource
的子类,让其遵守UITableviewDelegate
协议,进而可以实现对UITableview
的行高、组头部高等进行绑定。
网友评论