6

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
    }
}
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
Ctan Li
  • 177
  • 3
  • 13
  • This topic is not talked about anywhere, but it's possible. Instead of creating let layout = UICollectionViewCompositionalLayout(), you can directly create StretchyHeaderLayout() and that's it. – Faizyy Apr 18 '22 at 11:00

0 Answers0