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 に答える
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 に答える