5

尝试在组合布局中创建一个有弹性的标题,但到目前为止没有结果,我怎样才能在组合布局中实现这一点?谢谢!

检查了我能找到的所有示例,并且未谈论与组合布局相关的 UICollectionViewLayoutAttributes。

// 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
    }
}
4

0 回答 0