Override LayoutAttributesForElements in UICollectionViewCompositionalLayout to create a Stretchy Header?

1k Views Asked by At

Trying to create a stretchy header in Compositional Layout and so far no result, how can I achieve this in a Compositional Layout? Thanks!

Checked all samples I could find and non-talked about UICollectionViewLayoutAttributes in relation to Compositional layout.

// Creates the appropriate UICollectionViewLayout for each section type
func makeLayout() -> UICollectionViewLayout {
    // Constructs the UICollectionViewCompositionalLayout
    let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int, layoutEnv: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
    
    }

    let config = UICollectionViewCompositionalLayoutConfiguration()
    config.interSectionSpacing = 20
    layout.configuration = config
    return layout
}


class StretchyHeaderLayout: UICollectionViewFlowLayout {
    // we want to modify the attributes of our header component somehow
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect)
        layoutAttributes?.forEach { attribute in
                if attribute.representedElementKind == UICollectionView.elementKindSectionHeader {
                    guard let collectionView = collectionView else { return }
                    let contentOffsetY = collectionView.contentOffset.y
    
                if contentOffsetY < 0 {
                    let width = collectionView.frame.width
                    let height = attribute.frame.height - contentOffsetY
                    attribute.frame = CGRect(x: 0, y: contentOffsetY, width: width, height: height)
                }
            }
        }
        return layoutAttributes
    }
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
0

There are 0 best solutions below