首页 > 解决方案 > UICollectionView 自定义布局单元格类型相关属性

问题描述

我的集合视图具有动态布局和多种单元格/标题类型,我想仅将背景颜色应用于某些类型的标题。我尝试IndexPath在运行时确定这些标头的方法是:

class MyCustomLayout: UICollectionViewFlowLayout {

    private var backgroundAttrs = [UICollectionViewLayoutAttributes]()

    override func prepare() {
        super.prepare()

        guard let numberOfSections = collectionView?.numberOfSections else { return }            
        backgroundAttrs.removeAll()

        for section in 0 ..< numberOfSections {
            if let header = collectionView?
                .supplementaryView(forElementKind: UICollectionElementKindSectionHeader, 
                    at: IndexPath(item: 0, section: section)) as? HeaderThatNeedsBackground, 
               let attr = getBackgroundAttribute(forSection: section) {
                   backgroundAttrs.append(attr)
            }
        }
    }
    ...
}

supplementaryView(forElementKind:, at:)一直给我nil,所以循环永远不会执行。我的猜测是此时单元格尚未实例化?任何关于如何根据单元格/标题类型有选择地应用布局属性的建议将不胜感激

标签: iosswiftuicollectionviewuicollectionviewflowlayout

解决方案


首先,您不应该调用检索单元或补充视图的集合视图方法,因为集合视图使用布局(您正在实现的布局)来检索这些元素的信息。UICollectionViewLayout您可以在此链接中阅读如何正确子类化 a 。

在您的特定情况下,您需要覆盖该功能:

layoutAttributesForSupplementaryView(ofKind:at:)


推荐阅读