I have implemented a collection view to achieve a full screen image gallery where you can move between each image horizontally. I had a Flow Layout implemented, because it was a really simple layout, but I had problems invalidating its context to achieve the correct layout on device rotation.
That's where I switched to compositional layout, also with a really basic implementation:
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
layoutItem.contentInsets = .zero
layoutItem.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .none , top: .none, trailing: .none, bottom: .none)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
let layoutGroup = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [layoutItem])
layoutGroup.interItemSpacing = .fixed(0)
let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
layoutSection.interGroupSpacing = 0
layoutSection.orthogonalScrollingBehavior = .groupPaging
let collectionViewLayout = UICollectionViewCompositionalLayout(section: layoutSection)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .clear
collectionView.bounces = false
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "...")
And the problem is that whenever the device is rotated to landscape, the collection view seems to be scrolling to a different cell. On FlowLayout I had implemented the targetContentForOffset, and with that + overriding the invalidation context I could manage to set the correct offset for when the device is changing orientation.
But in this case, that method is never called and I can't find any other way to avoid the incorrect cell being displayed.
If I see the orientation change with Slow animation, the cell is changing even before the rotation started. I've tried scrolling to the "correct" cell with viewWillTransition (just to see if that works) and it doesn't, it keeps jumping to a different cell. So I don't even know if this is related to the targetContentOffset.
Here is a gif with the slow animation: https://gifyu.com/image/S3M3d. Note that on the video the cell is changing from 2nd to 1st, but if I'm on the 3rd cell, it changes to the 2nd one. So it seems it's always to the previous one.
Thanks in advance!