【问题标题】:Unable to dequeue view needed as cell for UICollectionView无法将 UICollectionView 的单元格所需的视图出列
【发布时间】:2016-08-30 20:27:07
【问题描述】:

我有一个带有自定义类的 UICollectionView,它是 UICollectionViewCell 的子类。我不断收到以下错误:

reason: '无法出列同类视图: 带有标识符 Appointment 的 UICollectionElementKindCell - 必须 为标识符注册一个 nib 或一个类或连接一个原型 故事板中的单元格'

然而,我做了以下事情:

用collectionView注册了自定义类。

self.collectionView.registerClass(AppointmentCollectionViewCell.self, forCellWithReuseIdentifier:"Appointment");

这是我的出队行:

let appointmentCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Appointment", forIndexPath: indexPath) as! AppointmentCollectionViewCell;

这就是我的 AppointmentCollectionViewCell 的样子:

class AppointmentCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var leftBorderView: UIView!
    @IBOutlet weak var appointmentLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func setAppointment(appointment:Appointment){
        self.leftBorderView.backgroundColor = appointment.eventColour;
        self.appointmentLabel.textColor = appointment.eventColour;
        self.backgroundColor = appointment.eventColour.colorWithAlphaComponent(0.2);
    }

}

我还在视图中提供了重用标识符为“约会”。

我还根据此处发布的答案尝试了以下方法 - 仍然无法正常工作:

let appointmentNib = UINib(nibName: "AppointmentCollectionViewCell", bundle:NSBundle.mainBundle())
        self.collectionView.registerNib(appointmentNib, forCellWithReuseIdentifier: "Appointment")

谷歌搜索后,大多数人忘记注册课程。就我而言,我已经注册了课程,但仍然不断收到错误消息。我哪里错了?

【问题讨论】:

  • 您是否在界面生成器中正确输入了“约会”?在情节提要中选择单元格后,打开属性检查器并检查标识符字段...?
  • @pedrouan,我已根据您的评论更新了帖子
  • 情节提要中的单元格标识符不是必需的如果您以编程方式注册单元格标识符
  • 如果单元格是故事板中的原型单元格,那么您不应该在代码中注册任何内容。
  • @dan 该单元格不是原型,它是一个自定义单元格

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

如果您的单元格与 xib 文件相关联,您需要使用 registerNib 方法,而不是 registerClass 方法。

func registerNib(_ nib: UINib?, forCellWithReuseIdentifier identifier: String)

Documentation

您似乎也混淆了 Collection Reusable View 和 UICollectionViewCell - 它是什么?两者都有特定的注册方法,查看文档。

【讨论】:

  • 我没有关注您上次发布的更新,“您似乎也混淆了 Collection Reusable View 和 UICollectionViewCell”,请详细说明,我可能会混淆一些东西
【解决方案2】:

第一次检查:

  1. 您有一个具有类 AppointmentCollectionViewCell

    的 Xib
  2. 从课堂上获取 Nib 例如 UINib *favouritesNib = [UINib nibFromClass:[TNYCellRestaurantAnchorclass]];

  3. 将 Nib 注册到 CollectionView

    [self.collectionViewName registerNib:nib forCellReuseIdentifier:@"identifier name"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    相关资源
    最近更新 更多