You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用UICollectionViewCompositionalLayout如何将头部文本置于cell上方

解决方案

你遇到的是布局元素层级问题,NSCollectionLayoutBoundarySupplementaryItem 默认的z轴层级低于单元格,所以会被蓝色cell盖住,只需要给头部补充视图设置更高的zIndex即可,修改后代码如下:

private func makeHelloLayoutSection() -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(
        widthDimension: .absolute(100),
        heightDimension: .absolute(200))
    let groupSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(0.8),
        heightDimension: .absolute(500))
    let supplementarySize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1),
        heightDimension: .absolute(50))

    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    let group = NSCollectionLayoutGroup.horizontal(
        layoutSize: groupSize,
        subitems: [item])

    let topInset = groupSize.heightDimension.dimension - itemSize.heightDimension.dimension
    group.contentInsets.top = topInset

    let section = NSCollectionLayoutSection(group: group)
    section.contentInsets.leading = 16
    section.orthogonalScrollingBehavior = .continuous
    
    let sectionBackgroundDecoration = NSCollectionLayoutDecorationItem.background(
        elementKind: sectionBackgroundDecorationElementKind)
    section.decorationItems = [sectionBackgroundDecoration]

    let sectionSupplementaryItem = NSCollectionLayoutBoundarySupplementaryItem(
        layoutSize: supplementarySize,
        elementKind: self.categoryHeaderID,
        alignment: .topLeading)
    // 新增这行,设置层级高于单元格
    sectionSupplementaryItem.zIndex = 10
    // 如果需要调整头部和下方cell的间距,可以再加这行调整底部内边距
    // sectionSupplementaryItem.contentInsets = .init(top: 0, leading: 0, bottom: 16, trailing: 0)
    section.boundarySupplementaryItems = [sectionSupplementaryItem]

    return section
}

zIndex数值越大,渲染层级越靠上,设置为大于0的数值即可保证头部显示在所有cell和装饰背景的上方。

如果调整后头部的位置和设计稿还有偏差,可以通过修改sectionSupplementaryItem的contentInsets或者section的contentInsets.top属性来微调垂直位置。

内容的提问来源于stack exchange,提问作者JEL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:45:08