我正在使用带有在Storyboard中定义的自定义布局类的UICollectionView来处理Circle Layout的示例。
是否有一种教程或逐步说明如何向使用自定义布局的集合视图添加补充视图?
我一直在查看Introducing Collection Views示例,但无法真正理解该项目中如何定义补充视图。它似乎是在流布局中使用Storyboard注册的,但我不知道该项目中的后续布局更改如何移动补充视图。
这个想法是在layoutAttributesForElements(in:)
中为补充视图返回UICollectionViewLayoutAttributes
。例如,在您的UICollectionViewLayout
子类中:
var headerAttributes: UICollectionViewLayoutAttributes!
override func prepare() {
headerAttributes = UICollectionViewLayoutAttributes(
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
with: IndexPath(item: 0, section: 0))
headerAttributes.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if headerAttributes.frame.intersects(rect) {
return [headerAttributes]
} else {
return nil
}
}
重要的是使用forSupplementaryViewOfKind:
初始化器创建属性。通过从这个方法返回补充视图的属性,集合视图知道这些视图存在的位置,并将调用collectionView(_:viewForSupplementaryElementOfKind:at:)
从其数据源获取实际视图。