0

何百ものセルを含む 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)
    }
}

これは多少機能しますが、ハッキーに思えます。これを達成するためのよりエレガントなソリューションが必要ですか?

4

0 に答える 0