ios - 无法将 UILabel 添加到 UICollectionViewCell

标签 ios swift uikit uilabel 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 返回该单元格,而不是通过出队

关于ios - 无法将 UILabel 添加到 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600956/

相关文章:

ios - Swift:使用字典中 ui 元素的值

ios - 在 SwiftUI 中切换 View 后 Firebase 图像为空

ios - Swift - 从模型中的 API 调用返回一个 JSON 对象作为字典以在 View Controller 中使用

ios - 像键盘一样显示 UIPickerView,没有 UITextField

ios - CGlayer 的内存问题

objective-c - 在 iOS 应用程序之间使用相同的身份验证凭据

ios - 为什么 iTunes Search API 的结果排序与 iOS 设备上的搜索结果不同?

ios - 弹回 subview 可加快视频速度

swift - "Cannot convert value of type ' () ' to UIImage": Swift

iphone - 如何使 NSDateFormatter 显示特定于语言环境的日期?