我正在尝试使我的tableView cells
可移动,但它需要来自UITableViewDataSource
协议的 2 或 3 个函数,如果我尝试在我的viewController
中实现委托,它将要求新UITableViewDiffableDataSource
已经涵盖的numberOfRowsInSection
和cellForRowAtIndexPath
功能。
如何在使用新UITableViewDiffableDataSource
时实现此行为?
我能够通过像这样对UITableViewDiffableDataSource
类进行子类化来做到这一点:
class MyDataSource: UITableViewDiffableDataSource<Int, Int> {
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// your code to update source of truth
// make a new snapshot from your source of truth
// apply(snapshot, animatingDifferences: false)
}
}
然后,您可以override
实现所需的任何数据源方法。
为了充实Tung Fam的答案,这里有一个完整的实现:
class MovableTableViewDataSource: UITableViewDiffableDataSource<Int, Int> {
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
super.tableView(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
var snapshot = self.snapshot()
if let sourceId = itemIdentifier(for: sourceIndexPath) {
if let destinationId = itemIdentifier(for: destinationIndexPath) {
guard sourceId != destinationId else {
return // destination is same as source, no move.
}
// valid source and destination
if sourceIndexPath.row > destinationIndexPath.row {
snapshot.moveItem(sourceId, beforeItem: destinationId)
} else {
snapshot.moveItem(sourceId, afterItem: destinationId)
}
} else {
// no valid destination, eg. moving to the last row of a section
snapshot.deleteItems([sourceId])
snapshot.appendItems([sourceId], toSection: snapshot.sectionIdentifiers[destinationIndexPath.section])
}
}
apply(snapshot, animatingDifferences: false, completion: nil)
}
}
如果设置为 true,它将崩溃animatingDifferences
(无论如何,这里不需要动画(。
我不确定打电话给super.tableView(move…)
是否必要,但这似乎没有任何伤害。