2

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

Jack Guo
  • 3,959
  • 8
  • 39
  • 60

1 Answers1

0

First of all, you shouldn't call collection view methods that retrieve cell or supplementary views, since the collection view uses the layout (the one you are implementing) to retrieve information for those elements. You can read how to properly subclass a UICollectionViewLayout in this link.

In your particular case you need to override the function:

layoutAttributesForSupplementaryView(ofKind:at:)

Reynaldo Aguilar
  • 1,906
  • 1
  • 15
  • 29