为了做到这一点,您需要做两件事之一。要么拉入 RxDataSource Cocoapod 并使用 TableViewSectionedDataSource 子类之一,要么创建自己的数据源。
制作数据源并不难。下面是一个例子:https://github.com/dtartaglia/RxMultiCounter/blob/master/RxMultiCounter/RxExtensions/RxSimpleAnimatableDataSource.swift 我在我的中使用了 DifferenceKit,但是如果你想要超级简单,你可以在你的 func tableView(_:observedEvent) 方法中调用 tableView.reloadData()。
这是一个例子:
//
// RxTableViewMovableRowDataSource.swift
//
// Created by Daniel Tartaglia on 12/19/18.
// Copyright © 2018 Daniel Tartaglia. MIT License.
//
import UIKit
import RxSwift
import RxCocoa
class RxTableViewMovableRowDataSource<E, Cell: UITableViewCell>: NSObject, RxTableViewDataSourceType, UITableViewDataSource {
init(identifier: String, configure: @escaping (Int, E, Cell) -> Void, canMoveRowAt: ((Int, E) -> Bool)? = nil) {
self.identifier = identifier
self.configure = configure
self.canMoveRowAt = canMoveRowAt
}
func tableView(_ tableView: UITableView, observedEvent: Event<[E]>) {
values = observedEvent.element ?? []
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! Cell
let row = indexPath.row
configure(row, values[row], cell)
return cell
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
let row = indexPath.row
return canMoveRowAt?(row, values[row]) ?? true
}
let identifier: String
let configure: (Int, E, Cell) -> Void
let canMoveRowAt: ((Int, E) -> Bool)?
var values: Element = []
}