使用UICollectionLayoutListConfiguration仅为指定section添加header的实现问题
实现方案
你当前的问题核心是全局设置了headerMode = .supplementary,系统会默认给所有section预留header位置,需要从布局配置和数据源回调两部分调整:
一、修改布局逻辑,按section差异化设置header规则
替换原collectionView初始化中的布局代码,改用section provider单独配置每个section的header模式:
lazy var collectionView: UICollectionView = { // 按section动态生成布局 let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in var listConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped) // 仅给需要header的section开启supplementary模式 if let sectionType = Section(rawValue: sectionIndex), sectionType == .bottomSection { listConfig.headerMode = .supplementary } else { // 其他section直接关闭header,不会预留header高度 listConfig.headerMode = .none } return NSCollectionLayoutSection.list(using: listConfig, layoutEnvironment: layoutEnvironment) } let view = UICollectionView(frame: .zero, collectionViewLayout: layout) // 原有cell、header的注册逻辑保留 return view }()
二、修正补充视图回调的返回逻辑
补全原supplementaryViewProvider的边界处理,不符合条件的场景直接返回nil即可:
dataSource.supplementaryViewProvider = { [weak self] collectionView, kind, indexPath in guard let self = self, let section = Section(rawValue: indexPath.section), section == .bottomSection, kind == UICollectionView.elementKindSectionHeader else { // 所有不需要header/不符合类型的请求直接返回nil return nil } // 这里返回你自定义的header视图,注意提前注册对应的复用ID let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "你的header复用ID", for: indexPath) // 配置header内容逻辑 return header }
注意事项
- 提前注册header的复用类/Xib,否则调用
dequeue时会崩溃 - 该方案相比全局开启header后返回空视图的性能更好,不需要header的section不会触发系统的视图创建逻辑,也不会出现空白header占位的问题
内容的提问来源于stack exchange,提问作者David Henry
相关产品推荐
相关产品推荐

