我正在处理Circle Layout的示例,使用 UICollectionView 和故事板中定义的自定义布局类。
是否有某种教程或逐步说明如何将补充视图添加到使用自定义布局的集合视图中?
我一直在查看Introducing Collection Views示例,但无法真正理解该项目中如何定义补充视图。似乎它们是使用流布局在情节提要中注册的,但我不知道该项目中的后续布局更改如何移动补充视图。
我正在处理Circle Layout的示例,使用 UICollectionView 和故事板中定义的自定义布局类。
是否有某种教程或逐步说明如何将补充视图添加到使用自定义布局的集合视图中?
我一直在查看Introducing Collection Views示例,但无法真正理解该项目中如何定义补充视图。似乎它们是使用流布局在情节提要中注册的,但我不知道该项目中的后续布局更改如何移动补充视图。
这个想法是您返回UICollectionViewLayoutAttributes
以获取 中的补充视图layoutAttributesForElements(in:)
。例如,在您的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:)
以从其数据源获取实际视图。