如何获取集合视图中装饰视图的实例?

how to get the instance of the decoration view in the collection view?

我已经实现了一个带有自定义布局的 UICollectionView。我知道如何为整个集合视图呈现视觉装饰,但不知道如何为每个部分呈现不同的图像。我需要通过 indexPath 获取装饰视图的实例。我在 Apple 文档上找到了这个:

使用此方法为集合视图中的装饰视图创建布局属性对象。装饰视图是一种补充视图,但不呈现由集合视图的数据源管理的数据。相反,它们主要为部分或整个集合视图呈现视觉装饰。

如何使用indexPath参数来标识给定的装饰视图由您决定。通常,您使用 decorationViewKind 参数来标识装饰视图的类型,并使用 indexPath 信息来区分该视图的不同实例。

谁能详细告诉我怎么做?

非常感谢!

回答我自己的问题! 感谢 this article

首先,subclass UICollectionViewLayoutAttributes 并添加任何你想要的 属性。

其次,在函数layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes!中设置属性.

第三,在 UICollectionReusableView class 中,覆盖函数 applyLayoutAttributes: 以获取包含您的 属性.[=16 的自定义 UICollectionViewLayoutAttributes 实例=]

完成!