使用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
相关产品推荐
相关产品推荐

