I have a UICollectionView
with a header of type UICollectionReusableView
.
In it, I have a label whose length varies by user input.
@Pim's answer worked for me but as @linus_hologram in the comment section mentioned this solution makes AutoLayout complain about unsatisfiable constraints. I found a simple workaround:
In collectionView(_:layout:referenceSizeForHeaderInSection:)
instead of getting a reference to the view that your instance of UICollectionView
wants to reuse using collectionView(_:viewForSupplementaryElementOfKind:at:)
just create an instance of your header view class on the fly and add a width constraint so that AutoLayout
will be able to calculate your header's width:
let headerView = YourCustomHeaderClass()
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.widthAnchor.constraint(equalToConstant: collectionView.frame.width).isActive = true
let size headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return size
return size