iOS 18+ UICollectionView背景装饰视图覆盖单元格问题求助
iOS 18+ UICollectionView背景装饰视图覆盖单元格的解决方案
问题场景
使用UICollectionViewCompositionalLayout添加分区背景装饰视图时,iOS 18及以上版本中装饰视图会覆盖单元格,iOS 17及以下版本显示正常。
解决方案
手动设置背景装饰视图的zIndex为负数,强制让它处于单元格层级后方。
修改后的布局代码
let itemSize = NSCollectionLayoutSize( widthDimension: .absolute(60), heightDimension: .absolute(100) ) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1), heightDimension: .absolute(100) ) let group = NSCollectionLayoutGroup.horizontal( layoutSize: groupSize, subitems: [item] ) let section = NSCollectionLayoutSection(group: group) // 创建背景装饰视图并设置zIndex let backgroundDecoration = NSCollectionLayoutDecorationItem.background(elementKind: "customBackgroundElementKind") backgroundDecoration.zIndex = -1 // 关键设置:将层级设为负数,确保在单元格后方 section.decorationItems = [backgroundDecoration] return section
原理说明
iOS 18对NSCollectionLayoutDecorationItem的默认层级规则做了调整,背景装饰视图不再默认处于单元格下方。通过将zIndex设置为负数,可以明确指定其渲染层级低于默认的单元格(单元格默认zIndex为0),从而恢复iOS 17及以下版本的预期表现。
额外验证
确保已正确注册装饰视图:
collectionView.register(CustomBackgroundView.self, forDecorationViewOfKind: "customBackgroundElementKind")
内容的提问来源于stack exchange,提问作者sunwukongTH
相关产品推荐
相关产品推荐

