4

我有以下课程:

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

3 回答 3

15

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

这应该看起来像:

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

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

于 2015-03-04T06:06:50.103 回答
2

您还可以为情节提要中的标题设置自定义类。如果您通过扩展添加流布局委托,这会派上用场。

Xcode 故事板

于 2019-11-26T23:16:49.357 回答
1

viewDidLoad() 中的 Swift 3

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 }
于 2017-03-10T18:42:19.020 回答