OGeek|极客世界-中国程序员成长平台

标题: ios - 无法将 UICollectionView 的单元格所需的 View 出列 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:24
标题: ios - 无法将 UICollectionView 的单元格所需的 View 出列

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

reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier Appointment - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

然而,我做了以下事情:

用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);
    }

}

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

enter image description here

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

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

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



Best Answer-推荐答案


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

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

Documentation

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

关于ios - 无法将 UICollectionView 的单元格所需的 View 出列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236530/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4