So this is an interesting issue we found with UICollectionViewFlowLayout
on iOS 10 (still an issue on 11) and using UICollectionViewFlowLayoutAutomaticSize
UICollectionViewFlowLayout
supports auto layout for cells very well, BUT it does not supports it for supplementary views. Each time when auto layout code updates cell's frame it does nothing with headers and footers. So you need to tell layout that it should invalidate headers and footers. And there is a method for this!
You should override UICollectionViewLayout
's func invalidationContext(forPreferredLayoutAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes: UICollectionViewLayoutAttributes)
and perform supplementary view invalidation in it.
Example:
override open func invalidationContext(forPreferredLayoutAttributes preferred: UICollectionViewLayoutAttributes,
withOriginalAttributes original: UICollectionViewLayoutAttributes)
-> UICollectionViewLayoutInvalidationContext {
let context: UICollectionViewLayoutInvalidationContext = super.invalidationContext(
forPreferredLayoutAttributes: preferred,
withOriginalAttributes: original
)
let indexPath = preferred.indexPath
if indexPath.item == 0 {
context.invalidateSupplementaryElements(ofKind: UICollectionElementKindSectionHeader, at: [indexPath])
}
return context
}
In example above I am using invalidation context provided by UICollectionViewFlowLayout
to invalidate header supplementary view if first cell in section was invalidated. You can use this method for footer invalidation as well.
I came across the same problem. UICollectionViewFlowLayoutAutomaticSize
doesn't work for supplementary views. Use the UICollectionViewDelegateFlowLayout
to give the size explicitly. Its better to calculate the sizes and use delegates as automatic size calculations causes lagging, at times.
use referenceSizeForHeaderInSection
and referenceSizeForFooterInSection
delegate methods to give the header and footer size explicitly.