将"UICollectionReusableView"类型的值转换为"MyApp.CSSectionHeader"时出错

fuz*_*uzz 4 casting uicollectionreusableview swift

我有以下课程:

class CSSectionHeader: UICollectionReusableView {

    @IBOutlet var textLabel: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

我然后尝试像下面这样投射它:

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
}
Run Code Online (Sandbox Code Playgroud)

问题是我收到以下错误:

Could not cast value of type 'UICollectionReusableView' (0x10ff4d140) to 'MyApp.CSSectionHeader' (0x10d775a70).
Run Code Online (Sandbox Code Playgroud)

Max*_*hev 14

为了能够解析自定义类的头,您必须在调用之前在collectionview中注册此类dequeueReusableSupplementaryViewOfKind.

这应该是这样的:

self.collectionView.registerClass(CSSectionHeader.self,
    forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, 
    withReuseIdentifier: "sectionHeader")
Run Code Online (Sandbox Code Playgroud)

你可以把它放在里面 viewDidLoad()

  • 对我来说,问题也出在自定义标头的 XIB 文件中。我一直收到错误,直到我打开 XIB 并手动更改标题视图的类(它是“UICollectionReusableView”)。 (3认同)