【问题标题】:TableView scrolling to top after applying UITableViewDiffableDataSource snapshot应用 UITableViewDiffableDataSource 快照后,TableView 滚动到顶部
【发布时间】:2022-01-13 05:53:55
【问题描述】:

我正在使用 UITableViewDataSourcePrefetching 进行分页。

这些值将从 Realm 本地存储中获取。

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

应用快照后,tableview 滚动到顶部。

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

如何防止滚动?

视频链接TableView_scroll_issue_video

鉴于我的代码 sn-p

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)
}

【问题讨论】:

    标签: ios swift uitableview diffabledatasource uitableviewdiffabledatasource


    【解决方案1】:

    您可以尝试以下方法:

    dataSource.applySnapshotUsingReloadData(snapshot, completion: nil)
    

    仅适用于 iOS 15.0

    【讨论】:

    • 不工作,同样的问题。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多