2017-04-24 36 views
0

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

} 
} 
+0

您是否製作您的自定義單元格的任何一個標籤出口? –

+0

是的,類設置爲CustomCollectionViewCell。我更新了覆蓋 – kangarooChris

回答

4

您需要在您的自定義單元格創建的UILableIBOutlet比你可以在你的cellForItemAt方法訪問這些lablecell.label

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

更新: enter image description here

打開故事板 - >選擇你的自定義單元 - >右側面板 - >身份檢查器 - >類名 - >在這裏寫你的類名。

+0

您需要在Storyboard中添加CustomCollectionViewCell類,而不是在課程中添加IBOutlet。 –

+0

結帳更新了答案 –

1

將您的CustomCollectionViewCell類的故事板選擇單元格,然後您可以爲您的標籤

class CustomCollectionViewCell: UICollectionViewCell { 
    @IBOutlet weak var lable: UILabel! 
} 
相關問題