Search code examples
iosuicollectionviewuikituicollectionviewlayout

UICollectionView custom layout. Supplementary views are not shown or queried


I am trying to create a simple custom layout for UICollectionView to use programmatically (i.e. without Interface Builder).

I do everything according to the docs:

  1. Subclass UICollectionViewLayout and prepare my layout
  2. override layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) and return corresponding layout attributes
  3. add collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) implementation where I return my supplementary view

My problem is that neither

collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath)

nor

layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath)

is getting called, so I can't see my supplementary views.

I have double-checked my implementations both for layout and for supplementary views creation but I still can't get it to work.


Solution

  • Apparently it is not enough to have

    layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
    

    which return attributes for supplementary views. One also needs to return attributes for supplementary views in

    layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
    

    My mistake was that I was only returning layout attributes for cells in

    layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
    

    Once I added layout attributes for supplementary views into values returned by

    layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
    

    I got my datasource methods called and supplementary views returned.

    EDIT: This answer covers iOS10 SDK. I haven't tried on earlier versions