gpt4 book ai didi

ios - 向上滚动时在 UICollectionView 中保持滚动位置

转载 作者:行者123 更新时间:2023-11-28 15:43:10 25 4
gpt4 key购买 nike

我有一个 UICollectionView,带有类似聊天的 View - 消息显示在底部,最新的消息。当用户向上滚动时,它会加载以前的消息并更新 Collection View 。我试图在添加新数据时保持 UICollectionView 的内容偏移量,但我无法让它工作。

这是我目前拥有的:

// First find the top most visible cell.
if let topCellIndexPath = collectionView.indexPathsForVisibleItems.sorted().first,
let topCell = collectionView.cellForItem(at: topCellIndexPath),
let topCellLayout = collectionView.layoutAttributesForItem(at: topCellIndexPath) {

// Save the y position of the top cell.
let previousTopCellY = topCellLayout.frame.origin.y

// Perform updates on the UICollectionView without animation (ignore the fact it says adapter)
adapter.performUpdates(animated: false) { [weak self] completed in
if let strongSelf = self,
let topCellNewIndexPath = strongSelf.collectionView.indexPath(for: topCell),
let newTopCellLayout = strongSelf.collectionView.layoutAttributesForItem(at: topCellNewIndexPath) {

// Calculate difference between the previous cell y value and the current cell y value
let delta = previousTopCellY - newTopCellLayout.frame.origin.y

// Add this to the collection view content offset
strongSelf.collectionView.contentOffset.y += delta
}
}
}

这个好像不行,更新后有时获取不到cell的indexPath

编辑基于@Arkku 的回答,这是可行的。虽然有一点点闪烁。

let previousContentSize = collectionView.contentSize.height
adapter.performUpdates(animated: false) { [weak self] completed in
if let strongSelf = self {
let delta = strongSelf.collectionView.contentSize.height - previousContentSize
strongSelf.collectionView.contentOffset.y += delta
}
}

最佳答案

正如我之前评论的那样,从 contentSize 获取 delta 可能比从特定单元格的来源获取更好。根据您自己的版本提出的建议:

let previousContentHeight = collectionView.contentSize.height
adapter.performUpdates(animated: false) { [weak self] completed in
guard let self = self else { return }
let delta = self.collectionView.contentSize.height - previousContentHeight
self.collectionView.bounds.origin.y += delta
}

关于ios - 向上滚动时在 UICollectionView 中保持滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com