Search code examples
swiftcastinguicollectionreusableview

Error casting value of type 'UICollectionReusableView' to 'MyApp.CSSectionHeader'


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).

Solution

  • 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()