首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用UITableView时移动UITableViewDiffableDataSource单元?

如何在使用UITableView时移动UITableViewDiffableDataSource单元?
EN

Stack Overflow用户
提问于 2019-08-15 13:45:19
回答 2查看 510关注 0票数 1

我试图使我的tableView cells可以移动,但是它需要来自UITableViewDataSource协议的2到3个函数,如果我试图在UITableViewDataSource协议中实现委托,它将请求使用已经被新的UITableViewDiffableDataSource覆盖的numberOfRowsInSectioncellForRowAtIndexPath函数。

如何在使用新UITableViewDiffableDataSource时实现此行为

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-18 09:39:31

为了充实Tung Fam的答案,下面是一个完整的实现:

代码语言:javascript
复制
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…),但似乎没有什么坏处。

票数 3
EN

Stack Overflow用户

发布于 2019-10-27 21:59:09

通过像这样对UITableViewDiffableDataSource类进行子类分类,我能够做到这一点:

代码语言:javascript
复制
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实现所需的任何数据源方法。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57510622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档