gpt4 book ai didi

ios - UICollectionView(自动调整大小).reloadData() 将 contentOffset 重置为 0(顶部)

转载 作者:搜寻专家 更新时间:2023-10-30 22:01:01 25 4
gpt4 key购买 nike

我有一个 UICollectionView 使用标准 UICollectionViewFlowLayout 并将 estimatedItemSize 设置为 UICollectionViewFlowLayoutAutomaticSize

调用 collectionView.reloadData() 后, View 的滚动位置将重置为 CGPoint(x: 0, y: 0)。我知道 .reloadData() 应该只作为最后的手段使用,但在我的场景中是必要的。到目前为止,我发现这可能是由于未通过 collectionView(_:layout:sizeForItemAt:) 返回项目大小引起的。 (任何类似于 UITableViewtableView:estimatedHeightForRowAtIndexPath: 的解决方案,如 in this StackOverflow answer 将不胜感激)。

最佳答案

在我的例子中,我修复了它:在这里我检测我的单元格是否完全可见,如果不是这样 - 移动到它。 (没有“跳跃”)

 let cellRect = collectionView.convert(cell.frame, to: collectionView.superview)
if !collectionView.frame.contains(cellRect) {
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
return collectionView.reloadData()
}

在这里,我持有我的 contentOffset:

   let currentContentOffSet = collectionView.contentOffset
if #available(iOS 12.0, *) {
UIView.animate(withDuration: 0) {
collectionView.reloadData()
collectionView.performBatchUpdates(nil, completion: { _ in
collectionView.contentOffset = currentContentOffSet
})
}
} else {
UIView.animate(withDuration: 0) {
collectionView.reloadItems(at: [self.lastSelectedIndexPath, indexPath])
collectionView.contentOffset = currentContentOffSet
}
}

如果单元格最近变得可见(或已经可见)并且我点击该单元格,它有助于移动到单元格。也没有“跳跃”(没有重置 contentOffset)

你也可以在 collectionViewController 中尝试这个:

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
if lastSelectedIndexPath != indexPath {
let cellRect = collectionView.convert(cell.frame, to: collectionView.superview)
if !collectionView.frame.contains(cellRect) {
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
} else {
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .init())
}
collectionView.deselectItem(at: lastSelectedIndexPath, animated: false)
lastSelectedIndexPath = indexPath
}
}

这在 collectionViewCellModel 中:

  override var isSelected: Bool {
didSet {
switch self.isSelected {
case false:

case true:

}
}
}

关于ios - UICollectionView(自动调整大小).reloadData() 将 contentOffset 重置为 0(顶部),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46827379/

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