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

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

我有以下 class:

class CSSectionHeader: UICollectionReusableView {

    @IBOutlet var textLabel: UILabel!

}

然后我尝试按如下方式转换它:

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
}

问题是我收到以下错误:

Could not cast value of type 'UICollectionReusableView' (0x10ff4d140) to 'MyApp.CSSectionHeader' (0x10d775a70).

为了能够双端 header 您的自定义 class,您必须在调用 dequeueReusableSupplementaryViewOfKind 之前在集合视图中 register 这个 class。

这应该是这样的:

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

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

Swift 3 在 viewDidLoad()

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

同时添加以下内容

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 }

您还可以为故事板中的页眉设置自定义 class。 如果您通过扩展添加流布局委托,这会派上用场。