我正在尝试将 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/