Search code examples
swiftuicollectionviewswift2uicollectionviewcellxcode7

custom UICollectionViewCell class recognize but not working


I implemented a custom class for my collectionview cells. The class recognize the attributes like labels but when i run my app the label text doesn't display. Class is register like this :

  self.collectionView!.registerClass(StatsCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

here is the init method of the custom cell class:

var textlabel = UILabel()

override init(frame: CGRect) {
    let width = frame.size.width
    let height = frame.size.height
    textlabel = UILabel(frame: CGRectMake(0, 0, width,height))
    super.init(frame: frame)
}

and the implementation :

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StatsCollectionViewCell

    // Configure the cell
    cell.textlabel.text = "test"

    return cell
}

Could someone point me to my mistake please, i'm a bit lost here, cannot see what's wrong.

Note that i can use the cell properties (meaning the cell is in fact here).


Solution

  • You didn't put textlabel in a view.

    override init(frame: CGRect) {
        let width = frame.size.width
        let height = frame.size.height
        textlabel = UILabel(frame: CGRectMake(0, 0, width,height))
        super.init(frame: frame)
        addSubview(textlabel) // add text label to view
    }