RxSwift + canMoveRowAt

RxSwift + canMoveRowAt

我正在使用 RxSwift (RxCocoa) 填充我的 tableView 单元格

viewModel.cellsDriver.drive(tableView.rx.items) { ... }

这样我就无法访问tableView的dataSource的方法

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool

但我需要为

指定哪些行是可移动的
tableView.rx.itemMoved

如何限制哪些行不能拖动?我宁愿避免使用 RxDataSources

为此,您需要执行以下两项操作之一。要么拉入 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 = []
}