首页 > 解决方案 > 将徽章(补充视图)添加到 UICollectionLayoutListConfiguration

问题描述

有什么办法可以添加一个徽章NSCollectionLayoutSupplementaryItem)到一个UICollectionLayoutListConfiguration

我正在尝试使用Modern Collection Views实现侧边栏:

var configuration = UICollectionLayoutListConfiguration(appearance: .sidebar)
...

let section = NSCollectionLayoutSection.list(using: configuration, layoutEnvironment: layoutEnvironment)

但我找不到如何实现badge配置:

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",
                containerAnchor: badgeAnchor)

就像 Apple 提供的示例代码一样:

let item = NSCollectionLayoutItem(layoutSize: itemSize, supplementaryItems: [badge])

(Apple提供的示例代码,顺便说一句)

关于如何将徽章实施UICollectionLayoutListConfiguration或不可能实施的任何想法?

标签: iosswiftuicollectionviewuikituicollectionviewlayout

解决方案


在示例项目中,元素类型badge错误。它是

let badge = NSCollectionLayoutSupplementaryItem(
            layoutSize: badgeSize,
            elementKind: ItemBadgeSupplementaryViewController.badgeElementKind,
            containerAnchor: badgeAnchor)

并且错误消息实际上是有道理的:

"the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath: does not match the element kind it is being used for. When asked for a view of element kind 'badge-element-kind' the data source dequeued a view registered for the element kind 'badge-reuse-identifier'."

只需elementKind将徽章(in ItemBadgeSupplementaryViewController)更改为

elementKind: BadgeSupplementaryView.reuseIdentifier

为了回答您的问题,徽章将是您的NSCollectionLayoutItem.


推荐阅读