0

I created a subclass of UICollectionReusableView. Then in the function

collectionViewTableLayoutManager(manager: collectionView: headerViewForRow row:  indexPath: )

I am trying to dequeue a view and cast it to the subclass.

Here's the start of the method:

func collectionViewTableLayoutManager(manager: DRCollectionViewTableLayoutManager!, collectionView: UICollectionView!, headerViewForRow row: UInt, indexPath: NSIndexPath!) -> UICollectionReusableView! {

    let view = collectionView.dequeueReusableSupplementaryViewOfKind(DRCollectionViewTableLayoutSupplementaryViewRowHeader, withReuseIdentifier: collectionViewHeaderIdentifier, forIndexPath: indexPath) as! CVHeaderView

It crashes at runtime on the "let view ... " with this error:

Could not cast value of type 'UICollectionReusableView' (0x103994fb8) to 'CollectionViewTableLayout.CVHeaderView' (0x1023f3bd0).

Here is my subclass code:

class CVHeaderView: UICollectionReusableView {

let textLabel: UILabel!

override init(frame: CGRect) {

    let textSize = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
    textLabel = UILabel(frame: textSize)

    super.init(frame: frame)

    textLabel.font = UIFont.systemFontOfSize(10)
    textLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
    textLabel.textAlignment = NSTextAlignment.Center
    textLabel.backgroundColor = UIColor.clearColor()


    self.addSubview(textLabel)


}

required init(coder aDecoder: NSCoder) {
...
}

I'm confused why I can't do this downcast. Is it somehow related to my use of the outside library of the DR... classes?

tangobango
  • 381
  • 1
  • 4
  • 17
  • 1
    You can't downcast because the object isn't of that type - as the exception says. The class that is associated with the reuse identifier you have specified is `UICollectionReusableView`, not your subclass. – Paulw11 Jul 10 '15 at 21:55
  • @Paulw11 Thanks. That pointed me in the right direction. After I built the subclass, I had forgotten to change my registerClass statement. All fixed now. – tangobango Jul 10 '15 at 22:06

1 Answers1

0

Thanks to Paulw11, I figured out what to do. I'll put the answer here for any other rookie trying to subclass after building app without the subclass.

After building the subclass, I needed to change my registerClass statement from:

collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: DRCollectionViewTableLayoutSupplementaryViewRowHeader, withReuseIdentifier: collectionViewHeaderIdentifier)

to

collectionView.registerClass(CVHeaderView.self, forSupplementaryViewOfKind: DRCollectionViewTableLayoutSupplementaryViewRowHeader, withReuseIdentifier: collectionViewHeaderIdentifier)

All fixed.

tangobango
  • 381
  • 1
  • 4
  • 17