0

I have a project that has UICollectionView which needs to have paging. I have set horizontal scroll and paging enabled. MinimumInteritemSpacing is 0. I need the cells to be the size of the collection view so I have:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return collectionView.frame.size

}

This sizes the cells properly for both portrait and landscape, but the offset on orientation change is wrong and two cells will be displayed at the same time. What is a good approach to be able to see the same cell on orientation change and for it to be taking up the whole collection view?

I have tried implementing collectionView(_:targetContentOffsetForProposedContentOffset:) This will fix the issue if you stay on one screen, but going to another screen, rotating and going back to the collection view screen will have a bug - there will be again two partially visible cells and the offset will not be the wanted one. This is why I guess there should be another solution to this issue.

surToTheW
  • 772
  • 2
  • 10
  • 34
  • try calling `collectionView.collectionViewLayout.invalidateLayout()` in `viewWillTransitionToSize` that should help – Sandeep Bhandari Oct 31 '18 at 10:41
  • @SandeepBhandari Thanks for the response. Tried your suggestion, but nothing changes. – surToTheW Oct 31 '18 at 10:52
  • Possible duplicate of [UICollectionView contentOffset after device rotation](https://stackoverflow.com/questions/41639968/uicollectionview-contentoffset-after-device-rotation) – DonMag Oct 31 '18 at 13:36
  • @DonMag I have checked the above solution but it does not work for all cases. I have edited my question. – surToTheW Oct 31 '18 at 13:47
  • @surToTheW - you probably also want to save the current offset (or center cell position?) in `viewWillDisappear` and then adjust the contentOffset when you return in `viewWillAppear` – DonMag Oct 31 '18 at 14:16
  • @DonMag Thanks for the suggestion. This would work unless you go to background, go to from portrait to landscape and go back to foreground. You could again save the offset and recalculate on coming to foreground but the thing is that if after rotating in background you double click the home button while the app is in background and look at the app in the open apps, it will show the current state - and it again will be broken (two visible cells) – surToTheW Oct 31 '18 at 15:51

0 Answers0