首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >应用TableView快照后,UITableViewDiffableDataSource滚动到顶部

应用TableView快照后,UITableViewDiffableDataSource滚动到顶部
EN

Stack Overflow用户
提问于 2021-12-08 09:00:29
回答 2查看 466关注 0票数 3

我正在使用UITableViewDataSourcePrefetching进行分页。

这些值将从域本地存储中提取。

我会得到一组对象。这些值将应用于现有的UITableViewDiffableDataSource数据源。

应用快照后,表视图滚动到顶部。

我已经验证了我所有的ChatMessage对象都有唯一的hashValues。

我怎样才能防止滚动?

链接到视频视频

给出我的代码片段

代码语言:javascript
复制
private func appendLocal(chats chatMessages: [ChatMessage]) {
    var sections: [String] = chatMessages.map({ $0.chatDateTime.toString() })
    sections.removeDuplicates()
    guard !sections.isEmpty else { return }
    var snapshot = dataSource.snapshot()
    let chatSections = snapshot.sectionIdentifiers
    sections.forEach { section in
        let messages = chatMessages.filter({ $0.chatDateTime.toString() == section })
        /// Checking the section is already exists in the dataSource
        if let index = chatSections.firstIndex(of: section) {
            let indexPath = IndexPath(row: 0, section: index)
            /// Checking dataSource already have some messages inside the same section
            /// If messages available then add the recieved messages to the top of existing messages
            /// else only section is available so append all the messages to the section
            if let item = dataSource.itemIdentifier(for: indexPath) {
                snapshot.insertItems(messages, beforeItem: item)
            } else {
                snapshot.appendItems(messages, toSection: section)
            }
        } else if let firstSection = chatSections.first {
            /// Newly receieved message's section not available in the dataSource
            /// Add the section before existing section
            /// Add the messages to the newly created section
            snapshot.insertSections([section], beforeSection: firstSection)
            snapshot.appendItems(messages, toSection: section)
        } else {
            /// There is no messages available append the new section and messages
            snapshot.appendSections([section])
            snapshot.appendItems(messages, toSection: section)
        }
    }
    dataSource.apply(snapshot, animatingDifferences: false)
}
EN

回答 2

Stack Overflow用户

发布于 2021-12-16 00:11:01

您可以尝试以下方法:

代码语言:javascript
复制
dataSource.applySnapshotUsingReloadData(snapshot, completion: nil)

它只能从iOS 15.0获得

使用UUID().uuidString也是常见的错误。

确保每个单元格的id是固定的。UITableViewDiffableDataSource将无法正确计算更改,如果更新id,它将重新加载整个表。

票数 0
EN

Stack Overflow用户

发布于 2022-05-09 05:45:19

您可以尝试创建一个新快照,而不是引用和更改dataSource的当前快照。

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

https://stackoverflow.com/questions/70272319

复制
相关文章

相似问题

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