自定义布局的UICollectionView - 如何/在哪里通过编程方式添加补充视图?

3
我正在使用带有在Storyboard中定义的自定义布局类的UICollectionView来处理Circle Layout的示例。 是否有一种教程或逐步说明如何向使用自定义布局的集合视图添加补充视图? 我一直在查看Introducing Collection Views示例,但无法真正理解该项目中如何定义补充视图。它似乎是在流布局中使用Storyboard注册的,但我不知道该项目中的后续布局更改如何移动补充视图。

5
这篇教程应该能帮助您回答您的问题:http://skeuo.com/uicollectionview-custom-layout-tutorial - topwik
使用此链接学习UICollectionVIewLayout:http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12 - Nathan
1个回答

3

这个想法是在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:)从其数据源获取实际视图。


这很正确,我花了大约1小时来解决这个问题,非常感谢你。 - Kishore Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接