我已经使用tableView
设置了Rx
,并允许用户使用cells
上下移动rx.itemMoved
:
let testData = BehaviorRelay<[String]>(value: ["hello", "hello again", "hello a third time"])
tableView.isEditing = true
testData.bind(to: tableView.rx.items(cellIdentifier:"cell")) { row, data, cell in
cell.textLabel?.text = data
}.disposed(by: disposeBag)
tableView.rx.itemMoved
.subscribe(onNext: { indexPaths in
//...
}).disposed(by:disposeBag)
它可以正常工作,以后我将indexPaths保存到
coreData
并使用该数据按照用户排列它们的顺序来设置tableView
cells
。但这是以后要解决的问题。首先,我想测试一下用一些虚拟的cells
重新排列data
,看看一旦cell
是row
,我是否可以更改tableView
populated
顺序。想象一下,这个虚拟的data
来自coreData
。我不知道该怎么做,但是我在这里找到了一些东西:https://github.com/ReactiveX/RxSwift/blob/master/Tests/RxCocoaTests/UITableView%2BRxTests.swift
我至少认为看起来像我所需要的。我在下面尝试过,但是它什么也没做:
let testRow = IndexPath(row: 0, section: 0)
let testRow2 = IndexPath(row: 2, section: 0)
tableView.dataSource!.tableView!(tableView, moveRowAt: testRow, to: testRow2)
我也试过
self.tableView.moveRow(at: testRow, to: testRow2)
逻辑似乎是我想要做的,但是什么也没有……那么我该怎么做呢?
最佳答案
为了重新排序项目,您必须在源处更改顺序并重新发射数组。这意味着您必须在中继上accept
一个新的数组。
像这样:
final class ExampleViewController: UITableViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let testData = BehaviorRelay<[String]>(value: ["hello", "hello again", "hello a third time"])
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.isEditing = true
tableView.dataSource = nil
testData.bind(to: tableView.rx.items(cellIdentifier:"cell")) { row, data, cell in
cell.textLabel?.text = data
}
.disposed(by: disposeBag)
tableView.rx.itemMoved
.subscribe(onNext: { indexPaths in
var items = testData.value
let item = items.remove(at: indexPaths.sourceIndex.row)
items.insert(item, at: indexPaths.destinationIndex.row)
testData.accept(items)
})
.disposed(by:disposeBag)
}
}
关于ios - 显示tableView时,如何将tableView单元排列为不同的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61893406/