iOS 10/11 UICollectionViewFlowLayout using UICollectionViewFlowLayoutAutomaticSize results in footer supplementary view misaligned

后端 未结 2 844
滥情空心
滥情空心 2021-01-31 10:23

So this is an interesting issue we found with UICollectionViewFlowLayout on iOS 10 (still an issue on 11) and using UICollectionViewFlowLayoutAutomaticSize

相关标签:
2条回答
  • 2021-01-31 10:29

    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.

    0 讨论(0)
  • 2021-01-31 10:54

    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.

    0 讨论(0)
提交回复
热议问题