我有一个带有自定义类的 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 中提供了重用标识符“Appointment”。
我还根据此处发布的答案尝试了以下方法 - 仍然无法正常工作:
let appointmentNib = UINib(nibName: "AppointmentCollectionViewCell", bundle:NSBundle.mainBundle())
self.collectionView.registerNib(appointmentNib, forCellWithReuseIdentifier: "Appointment")
谷歌搜索后,大多数人忘记注册类(class)。就我而言,我已经注册了该类(class),但仍然不断收到错误消息。我哪里错了?
最佳答案
如果您的单元格与 xib 文件关联,您需要使用 registerNib 方法,而不是 registerClass 方法。
func registerNib(_ nib: UINib?, forCellWithReuseIdentifier identifier: String)
您似乎还混淆了 Collection Reusable View 和 UICollectionViewCell - 是哪个?两者都有具体的注册方式,查看文档。
关于ios - 无法将需要作为 UICollectionView 单元格的 View 出队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236530/