如何为UICollectionLayoutListConfiguration添加NSCollectionLayoutSupplementaryItem徽章?
给UICollectionLayoutListConfiguration添加徽章的实现方案
可以给UICollectionLayoutListConfiguration生成的列表布局添加徽章,你之前运行官方示例崩溃通常是因为布局配置不匹配、缺少补充视图注册或数据源实现,不是该场景本身不支持。
具体实现步骤
1. 调整列表Section的布局配置
你正常生成列表Section之后,手动修改它内部默认的布局项,添加上徽章的补充布局即可:
var configuration = UICollectionLayoutListConfiguration(appearance: .sidebar) // 原有列表配置逻辑,比如头部、滑动操作等配置 let section = NSCollectionLayoutSection.list(using: configuration, layoutEnvironment: layoutEnvironment) // 新增徽章布局配置 let badgeAnchor = NSCollectionLayoutAnchor(edges: [.top, .trailing], fractionalOffset: CGPoint(x: 0.3, y: -0.3)) let badgeSize = NSCollectionLayoutSize(widthDimension: .absolute(20), heightDimension: .absolute(20)) let badge = NSCollectionLayoutSupplementaryItem( layoutSize: badgeSize, elementKind: "badge_element_kind", // 该标识要全局唯一,后续注册、数据源都要用到 containerAnchor: badgeAnchor ) // 列表布局默认只有一个全局的item配置,直接修改它的补充项即可 if let listItem = section.items.first { listItem.supplementaryItems = [badge] }
2. 注册徽章视图并实现数据源
你需要给UICollectionView注册对应类型的补充视图,同时实现补充视图的数据源回调:
// 首先注册你自定义的徽章视图(示例中自定义类为BadgeView) collectionView.register( BadgeView.self, forSupplementaryViewOfKind: "badge_element_kind", withReuseIdentifier: "BadgeViewReuseID" ) // 如果使用UICollectionViewDiffableDataSource,配置补充视图提供者 dataSource.supplementaryViewProvider = { collectionView, elementKind, indexPath in guard elementKind == "badge_element_kind" else { return nil } let badgeView = collectionView.dequeueReusableSupplementaryView( ofKind: elementKind, withReuseIdentifier: "BadgeViewReuseID", for: indexPath ) as! BadgeView // 给当前indexPath对应的徽章赋值,比如未读数量 let currentItem = dataSource.itemIdentifier(for: indexPath) badgeView.unreadCount = currentItem?.unreadCount ?? 0 // 如果不需要显示徽章,可直接设置hidden或者返回高度为0的视图 badgeView.isHidden = currentItem?.unreadCount == 0 return badgeView }
常见崩溃原因排查:
elementKind字符串在布局定义、视图注册、数据源回调三个位置不一致- 没有注册对应类型的补充视图,或者缺少补充视图的数据源实现
- 自定义创建的
NSCollectionLayoutItem没有正确绑定到当前使用的Section中
内容的提问来源于stack exchange,提问作者pableiros
相关产品推荐
相关产品推荐

