Can't add textLabel to a UICollectionViewCell?

EthanW picture EthanW · Dec 17, 2014 · Viewed 7.8k times · Source

I have a class file that is a subclass of the UICollectionViewController class. In my cellForItemAtIndexPath method, I am trying to set the textLabel of the cells. However, there is no textLabel option in the completions. This is the method so far:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    // Configure the cell
    cell.backgroundColor = cellColor ? UIColor.blueColor() : UIColor.orangeColor()
    //cell.textLabel.text = "Text"???
    switch indexPath.item {
    case 0...5:
        cellColor = true
    case 6...13:
        cellColor = false
    default:
        cellColor = true
    }
}

What can I do to add the textLabel to the cells?

Answer

Ezimet picture Ezimet · Dec 17, 2014

Unlike tableViewCell ,UICollectionViewCell doesn't have textLabel. You need to add the UILabel to cell's content view example:

var title = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 40))
cell.contentView.addSubview(title)