4

I have the following class:

class CSSectionHeader: UICollectionReusableView {

    @IBOutlet var textLabel: UILabel!

}

I'm then trying to cast it like the following:

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    let cell1 = UICollectionReusableView()

    if (kind == UICollectionElementKindSectionHeader) {
        // Throws the cast error here:
        let cell: CSSectionHeader = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "sectionHeader", forIndexPath: indexPath) as! CSSectionHeader

        return cell
    } else if (kind == CSStickyHeaderParallaxHeader) {
        let cell: UICollectionReusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! UICollectionReusableView

        return cell
    }

    return cell1
}

The problem is I'm getting the following error:

Could not cast value of type 'UICollectionReusableView' (0x10ff4d140) to 'MyApp.CSSectionHeader' (0x10d775a70).
gotnull
  • 26,454
  • 22
  • 137
  • 203

3 Answers3

16

In order to be able to deque header of your custom class you have to register this class in collectionview before calling dequeueReusableSupplementaryViewOfKind.

This should look like:

self.collectionView.registerClass(CSSectionHeader.self,
    forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, 
    withReuseIdentifier: "sectionHeader")

You can place it inside viewDidLoad()

Max Komarychev
  • 2,836
  • 1
  • 21
  • 32
  • 2
    For me problem was also in the custom header's XIB file. I was keep getting error until I open the XIB and manually changed class of header view (it was `UICollectionReusableView`). – tagirkaZ May 24 '21 at 09:51
2

You can also set the custom class for the header in the storyboard. This comes in handy if you are adding the Flow Layout delegate via an extension.

Xcode storyboard

Bilbo Baggins
  • 3,644
  • 8
  • 40
  • 64
1

Swift 3 in viewDidLoad()

self.collectionView.registerClass(CSSectionHeader.self,
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, 
withReuseIdentifier: "sectionHeader")

Also add the following

func collectionView(_ collectionView: UICollectionView,
                    viewForSupplementaryElementOfKind kind: String,
                    at indexPath: IndexPath) -> UICollectionReusableView{
    let headerView: CSSectionHeader  = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:"sectionHeader", for: indexPath) as! CSSectionHeader
    return headerView }
Alisha G
  • 41
  • 2