I have a problem that I cannot resolve at the moment namely I’m trying to set a different number of columns in the collection view based on the iPad position (collection should update on device rotation)
Currently, (depending on how the device is positioned on start) on the first rotation items width is not calculated properly:
It’d be great if someone could help and point out where is an issue.
Code for this project is on my GitHub: https://github.com/ceboolion/compositionalLayout
Thanks for your help.
2
Answers
I gave your UICollectionView a background of orange and ran your code and got similar results:
I noticed few things
func relayoutCollectionView(with size: CGSize)
function to see what the dimensions are when you want update the layout calculations and columnsWhen I turned from portrait to landscape, the output printed was
Collection View Width: 810.0, Collection View Height: 1080.0
which does not seem to be right.So from this I assume that it is too early for invalidateLayout to be called to get the right calculations.
When I do something like this from a UIViewController, I will make
invalidateLayout()
call fromviewWillLayoutSubviews()
In your case, what I tried and worked was adding the similar
override func layoutSubviews()
in yourclass CollectionView: UIView
I removed
relayoutCollectionView
from yourfunc relayoutCollectionView
Now it seems to work for the first time as well although I can still not explain why your current works every other time except for the first time.
Just as top answer say, it will rotaion to wrong layout after scroll collection.
I try to set animated to false, it work!
But I can’t explain why.