我有一个包含数百个单元格的 UICollectionView。当我向下滚动到一组特定单元格并旋转设备时,以前可见的单元格大部分时间都变得不可见(contentOffset 错误)。
这是我为保持单元格可见所做的:
var currentCenterIndexPath = IndexPath(item: 0, section: 0)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let center = view.convert(collectionView.center, to: collectionView)
currentCenterIndexPath = collectionView.indexPathForItem(at: center) ?? IndexPath(item: 0, section: 0)
coordinator.animate(alongsideTransition: { [unowned self] _ in
collectionView.scrollToItem(at: currentCenterIndexPath, at: .centeredVertically, animated: false)
})
}
现在,如果在另一个 ViewController 处于活动状态时设备已旋转并且我返回到持有 UICollectionView 的 ViewController,则偏移量再次错误。这就是我所做的:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !collectionView.indexPathsForVisibleItems.contains(currentCenterIndexPath) {
collectionView.scrollToItem(at: currentCenterIndexPath, at: .centeredVertically, animated: true)
}
}
这有点工作,但对我来说似乎很老套。必须有一个更优雅的解决方案来实现这一点?