我试图使我的tableView cells可以移动,但是它需要来自UITableViewDataSource协议的2到3个函数,如果我试图在UITableViewDataSource协议中实现委托,它将请求使用已经被新的UITableViewDiffableDataSource覆盖的numberOfRowsInSection和cellForRowAtIndexPath函数。
如何在使用新UITableViewDiffableDataSource时实现此行为
发布于 2020-03-18 09:39:31
为了充实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)
}
}如果animatingDifferences设置为true,它就会崩溃(在这里,动画并不是真正需要的)。
我不确定是否有必要打电话给super.tableView(move…),但似乎没有什么坏处。
发布于 2019-10-27 21:59:09
通过像这样对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实现所需的任何数据源方法。
https://stackoverflow.com/questions/57510622
复制相似问题