【问题标题】:UICollectionView custom layout cell-type-dependent attributeUICollectionView 自定义布局单元格类型相关属性
【发布时间】:2018-04-25 20:12:43
【问题描述】:

我的集合视图具有动态布局和多种单元格/标题类型,我想仅将背景颜色应用于某些类型的标题。我尝试在运行时确定这些标头的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,所以循环永远不会执行。我的猜测是此时单元格尚未实例化?任何关于如何根据单元格/标题类型有选择地应用布局属性的建议将不胜感激

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewflowlayout


    【解决方案1】:

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

    在您的特定情况下,您需要覆盖该函数:

    layoutAttributesForSupplementaryView(ofKind:at:)

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 2013-03-05
      • 2021-06-19
      相关资源
      最近更新 更多