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

后端 未结 2 848
滥情空心
滥情空心 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.

提交回复
热议问题