ios - 无法将需要作为 UICollectionView 单元格的 View 出队

标签 ios swift uicollectionview uicollectionviewcell

我有一个带有自定义类的 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”。

enter image description here

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

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)

Documentation

您似乎还混淆了 Collection Reusable View 和 UICollectionViewCell - 是哪个?两者都有具体的注册方式,查看文档。

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

相关文章:

ios - 横向模式下 UITextField 中间出现奇怪的黑条

ios - 如何使用 swift 执行SelectorOnMainThread 并在不使用闭包的情况下获取返回值?

ios - objective-c/JSON : How to get ObjectForKey when it's a top level object

ios - 垂直对齐具有不同字体大小的标签,Swift

ios - 从表格 View 中删除不必要的行

ios - 使用正交滚动行为的水平 uicollectionview 中的大差距

ios - 为什么 insetForSectionAt UICollectionView 委托(delegate)不在 iOS Swift 3 中调用?

ios - 从 Collection View 返回正确的图像

ios - 无法在 iphone 6 上检测到 ibeacon

iOS:以编程方式创建的 UINavigationController 的导航栏未扩展到安全区域