I have header (a UICollectionReusableCell) in a UICollectionView whose height needs to be variable. How can I have it resize itself according to the height of its contents?
I do not need to support iOS 7, and Autolayout solutions are preferable (if they exist).
This is how I solved it. I wish it was more elegant.
UILabel in the header view to have a numberOfLines value of 0. This will let it resize itself.collectionView(_:layout:referenceSizeForHeaderInSection:) instantiate a header from the xib. We'll use it to compute a size.setNeedsLayout and layoutIfNeeded.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) to compute the height.Notes:
The header must be moved out of the storyboard and into a xib because calling dequeuReusableSupplementaryViewOfKind from systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) causes a crash.
The header view must be able to compute a correct height only knowing its content and the desired width. This took some fiddling with the constraints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With