无法将 UILabel 添加到 UICollectionViewCell

Can't add UILabel to UICollectionViewCell

我正在尝试将 UILabel 添加到自定义 UICollectionViewCell。在我的 UICollectionViewCell 上,我创建了一个方法,该方法将实例化 UILabel 并将其添加到其中:

class VideoCell: UICollectionViewCell {

    func showOptions() {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 25))
        label.text = "test"
        contentView.addSubview(label)
    }

}

因此,当点击单元格时,我将调用此方法:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? VideoCell else {
        fatalError("Wrong instance for dequeued cell")
    }
    cell.showOptions()
}

虽然没有出现错误,但标签没有出现在单元格中。

我是不是遗漏了什么?

错误在这里

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? VideoCell else {
    fatalError("Wrong instance for dequeued cell")
}

您必须使用 cellForItemAtIndexPath 来 return 该单元格,而不是通过出队

详细说明@Sh_Khan 的答案,代码应如下所示:-

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? VideoCell
    return cell ?? UICollectionViewCell()
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) as? VideoCell else {
        fatalError("Wrong instance for dequeued cell")
    }
    cell.showOptions()
}