For UICollectionView's dynamic height cells we use,
if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}
with the proper constraint of height and width, it works fine with iOS 11.* versions but it breaks and does not make the cells dynamic for iOS 12.0
In my case, I solved this by explicitly adding the following constraints to the cell's contentView.
These constraints are already in place inside the xib of the cell, but somehow they aren't enough for iOS 12.
The other threads that suggested calling
collectionView.collectionViewLayout.invalidateLayout()
in various places didn't help in my situation.Sample code here: https://github.com/larrylegend/CollectionViewAutoSizingTest
This applies the workaround to code from a tutorial by https://medium.com/@wasinwiwongsak/uicollectionview-with-autosizing-cell-using-autolayout-in-ios-9-10-84ab5cdf35a2:
i have the same problem. using UILabels to size the collectionview. if i run
collectionView.collectionViewLayout.invalidateLayout()
before reloading the data it does an ok job of sizing the labels.still not quite right. it's tough for me to figure because i'm running it on the simulator vs. device.
Objective C version of above answer:
For Objective-C lovers like me ;) cheers !!!
I managed to solve this problem by putting such code into my subclass of UICollectionViewCell
and subclassing UICollectionView like this
Based on
ale84
's answer and because of the fact I needed that iOS 12 fix in multiple places I created a UICollectionViewCell extension which I named UICollectionViewCell+iOS12:And then in your collection view cells we do something like this (if your cell is created in IB):