如何使用Compositional Layout将头部固定在顶部?
使用Compositional Layout实现全局固定头部

要让头部在整个滚动过程中保持固定,核心是将头部作为UICollectionView的全局补充视图,而非绑定到单个section,具体实现步骤如下:
1. 注册头部补充视图
先为UICollectionView注册自定义头部视图类:
collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header")
2. 构建全局固定的头部布局
创建布局时,不要将头部添加到单个section的boundarySupplementaryItems,而是通过布局的全局配置绑定头部:
// 定义头部尺寸 let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(60)) // 创建全局头部补充项 let header = NSCollectionLayoutBoundarySupplementaryItem( layoutSize: headerSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top ) // 关键设置:固定到可视区域,且提升层级避免被遮挡 header.pinToVisibleBounds = true header.zIndex = 10 // 构建普通内容section let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(100)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let group = NSCollectionLayoutGroup.horizontal(layoutSize: itemSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) // 创建布局并绑定全局头部 let layout = UICollectionViewCompositionalLayout(section: section) { _, _ in return [header] }
3. 实现补充视图数据源方法
在UICollectionViewDataSource中返回头部视图并配置内容:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader else { return UICollectionReusableView() } let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! HeaderView header.titleLabel.text = "全局固定头部" return header }
4. 注意事项
- 若头部被导航栏遮挡,可设置
collectionView.contentInsetAdjustmentBehavior = .never,并手动调整头部的top约束或collectionView的contentInset。 - 多section场景下该方案依然有效,头部会始终固定在可视区域顶部,不受section滚动影响。
- 如需动态调整头部高度,可在
collectionView(_:layout:referenceSizeForHeaderInSection:)中返回对应尺寸,需与布局中的heightDimension匹配。
内容的提问来源于stack exchange,提问作者Danil N.
相关产品推荐
相关产品推荐

