2

I have a UICollectionViewController and want to add a custom header.

I checked Section Header in the Interface Builder within my CollectionViewController and implemented in my subclass of it the viewForSupplementaryElementOfKind function.

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionElementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "myHeaderIdentifier", for: indexPath)

        // !! NOT WORKING PROPERLY
        // sectionHeader overlaps other cells

        headerView.backgroundColor = UIColor(hue: 0.9, saturation: 1.0, brightness: 0.9, alpha: 1.0)
        headerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250.0)

        return headerView

    default:
        assert(false, "Unexpected element kind")
    }

}

The changes take effect, but the header (the pink area in the screenshot below) now overlaps the regular cells within the collectionView.

enter image description here

What am I doing wrong? Appreciate any help!

ixany
  • 5,433
  • 9
  • 41
  • 65

2 Answers2

3
public func layoutAttributesForSupplementaryElementOfKind(kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?

Here I believe you should be able to set the frame / height

There's also headerReferenceSize in UICollectionViewFlowLayout that you can set when creating your collectionView if it's going to be static

Magoo
  • 2,552
  • 1
  • 23
  • 43
  • Thank you, Magoo! Using FlowLayout led me into the right direction, `headerReferenceSize` does exactly what I wanted to achieve. `let flowLayout = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout` – ixany Nov 21 '16 at 09:20
  • Perfect, glad you got it sorted – Magoo Nov 21 '16 at 11:06
2

Use this method from the UICollectionViewDelegateFlowLayout protocol:

optional func collectionView(_ collectionView: UICollectionView, 
                  layout collectionViewLayout: UICollectionViewLayout, 
      referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 250.0)
}

Make sure to set your class as the flow layout's delegate. You can find more information here.

Mark
  • 7,167
  • 4
  • 44
  • 68