我正在使用自定义 CollectionViewCell,当我想将文本添加到自定义单元格时,我很难做到这一点。在我遵循的教程中,它只是说 cell.label.text,但我似乎无法在此处执行此操作。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell
// Configure the cell
cell.label.text = "Sec \(indexPath.section)/Item \(indexPath.item)" /////error here: CustomCollectionViewCell does not have the member label.
return cell
}
自定义的CollectionViewCell定义如下:
import UIKit
@IBDesignable
class CustomCollectionViewCell: UICollectionViewCell {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect){
super.init(frame: frame)
setup()
}
func setup(){
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.black.cgColor
self.layer.cornerRadius = 5.0
}
}
最佳答案
您需要在自定义单元格中创建 UILable
的 IBOutlet
,然后才能访问那些 lable
,例如 cell.label
在你的 cellForItemAt
方法中
class CustomCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var lable: UILabel! //write this line and connect lable in storyboard.
}
打开 Storyboard -> 选择您的自定义单元格 -> 右面板 -> 身份检查器 -> 类名 -> 在这里写下你的类名。
关于ios - 为什么我不能在自定义单元格中使用标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43579758/