My collection view has a dynamic layout and multiple cell/header types, and I would like to apply background color to only certain types of headers. The way I tried, unsuccessfully, to determine the IndexPath
of those headers during run time is:
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:)
keeps giving me nil
, so the loop is never executed. My guess is that the cells are not yet instantiated at this point? Any advice on how to selectively apply layout attribute based on cell/header type would be appreciated