ios - 为什么我不能在自定义单元格中使用标签

标签 ios swift uicollectionview

我正在使用自定义 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

}
}

最佳答案

您需要在自定义单元格中创建 UILableIBOutlet,然后才能访问那些 lable,例如 cell.label 在你的 cellForItemAt 方法中

class CustomCollectionViewCell: UICollectionViewCell {
     @IBOutlet weak var lable: UILabel! //write this line and connect lable in storyboard.
}

更新: enter image description here

打开 Storyboard -> 选择您的自定义单元格 -> 右面板 -> 身份检查器 -> 类名 -> 在这里写下你的类名。

关于ios - 为什么我不能在自定义单元格中使用标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43579758/

相关文章:

ios - 如何让 UITableViewController 在两个不同的高度显示两个不同的 UITableViewCell?

swift - 钥匙串(keychain) SecItemUpdate 返回 errSecParam

ios - 如何正确抽象 Firebase

ios - UICollectionview 委托(delegate)和数据源未开始调用

ios - 为什么 NSHTTPURLResponse 返回 nil? NSURLSession, swift 2.2

ios - 如何更改 iOS 7 中未选中的选项卡栏项目的颜色?

ios - 无法使用 Bootstrap 让我的 iPhone 横向媒体查询正常工作

swift - 从 Swift NSURLsession 的 Rest API 调用返回数据

ios - 从 UICollectionViewCell 传播自定义事件

ios - 如何使用异步图像实现 UICollectionViewDelegateFlowlayout 的 sizeForItemAtIndexPath?