【问题标题】:Why can i not downcast UICollectionViewCell to a subclass thereof?为什么我不能将 UICollectionViewCell 向下转换为它的子类?
【发布时间】:2016-08-24 20:55:47
【问题描述】:

我正在制作一个集合视图,并制作了我自己的自定义 collectionCell。我已经在身份检查员中指定了,据我所知,我做的一切都是正确的。

代码是

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)"

【问题讨论】:

  • 您确定要从正确的单元格中出列吗?确保重用标识符是正确的,并确保您在界面构建器中设置了自定义单元格。

标签: swift casting uicollectionview


【解决方案1】:

参考:Could not cast value of type 'UICollectionViewCell'

如果您在您的 collectionViewController 中看到此内容,请将其删除。 self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

【讨论】:

    【解决方案2】:

    发生的情况是,在 viewDidLoad() 中,Xcode 会自动生成这样的一行来定义单元格:

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

    您正在创建自己的方法来执行此操作,因此,您需要擦除 Xcode 在 vi​​ewDidLoad() 中自动生成的行

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 这是一个问题,而不是一个答案。应该作为评论发布。
      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多