UICollectionView with automatic cell customization does not correctly position the secondary view

I am using a UICollectionView with a flow layout and am trying to get CollectionView to appropriately determine the cell sizes according to AutoLayout restrictions.

While the cells are working as intended, I run into problems with the layout of any additional views that I add to the CollectionView.

In particular, the additional representation will be in the wrong position (that is, the original y value is incorrect) on the initial layout before β€œcorrecting” itself after scrolling.

enter image description here

For reference, here is how I adjust the cell size:

1. Set the size of the collectionViewLayout design element

let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.estimatedItemSize = CGSizeMake(375, 50.0)
    layout.minimumInteritemSpacing = 0.0
    layout.minimumLineSpacing = 0.0
    let view = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
    view.backgroundColor = UIColor.whiteColor()
    view.alwaysBounceVertical = true
    return view
}()

2. Use subclasses of AutoLayoutCollectionViewCell

class AutoLayoutCollectionViewCell: UICollectionViewCell {
    override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        layoutIfNeeded()
        layoutAttributes.bounds.size.height = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        return layoutAttributes
    }
}

, .

- , .

3.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSizeMake(CGRectGetWidth(collectionView.frame), 30.0) 

}

: ? ? View, ?

+6
1

, UICollectionViewFlowLayout :

override func invalidationContext(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext {
    let context = super.invalidationContext(forPreferredLayoutAttributes: preferredAttributes, withOriginalAttributes: originalAttributes)
    context.invalidateSupplementaryElements(ofKind: UICollectionElementKindSectionHeader,
                                                at: [originalAttributes.indexPath])
    return context
}
+3

Source: https://habr.com/ru/post/1016148/


All Articles