I started to use AutoLayout for a large project and was positively surprised about it. However, now I have to adjust the project to accommodate for rotation and size classes, and I have big troubles getting the views to behave correctly.
The base problem is that I have UICollectionViews
with cells that again contain UICollectionViews. When the device is rotated, the base collection view adapts it's cells right, but all cells of the nested collection views are not adjusted to the new size automatically.
After investigation it comes down to:
viewWillTransitionToSize
is called, the base collection view is not rotated yet (as expected)coordinator animateAlongsideTransition ... completion:{}
block in viewWillTransitionToSize
the cells do not have their new width yet.The above means that there is no place where I could possible tell the cells of the nested collection views to change their size, as I don't know the new widths yet; and the autolayout system does not automatically adjust them.
Does anyone else have the same problem or know a solution?
Answering my own question here - I finally found the solution. For any others who are having troubles with this here is what I did:
The main part lies in putting invalidateLayout
and reloadData
calls in the right places:
invalidateLayout
on the base collectionView's layout in the willTransitionToSize
function.reloadData
on the base collectionView in the completion block of a coordinator animateAlongsideTransition:
call in the willTransitionToSize
function.prepareLayout
function of the collection view layout, make sure the pre-calculated cell sizes use the right width, I used a wrong width here which lead to some additional problems.