为什么我无法将UICollectionViewCell向下转型为其子类?

5
我正在制作一个集合视图,并制作了自己的自定义集合单元格。我已在“身份检查器”中指定了这一点,据我所知,我已经做得很正确。
代码如下:
import UIKit

class SubjectCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var label: UILabel!
}

并且在我的collectionViewController中

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SubjectCollectionViewCell

    return cell
}

我收到了以下错误信息

"无法将类型“UICollectionViewCell”(0x110460820)转换为类型“project.SubjectCollectionViewCell”(0x10eceeda0)。 (lldb)"


4
你确定正在出队列正确的单元格吗?确保重用标识符是正确的,同时在界面构建器中设置你的自定义单元格类。 - almas
3个回答

12

3

发生的事情是,在viewDidLoad()中,Xcode会自动产生以下一行代码来定义单元格:

self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

由于您正在创建自己的方法来完成此操作,因此您需要删除在viewDidLoad()中由Xcode自动生成的该行代码。


-2

你是否注册了reuseIdentifier,以便它可以创建正确类的对象?


2
这是一个问题,不是答案。应该发布为评论。 - rmaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接