Set a custom CollectionViewCells label in ViewControllers cellForItemAt indexPath method

I have been trying to set my Custom collection view cells UILabel text with the following code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell: AlbumCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! AlbumCollectionViewCell

    //set label text
    cell.albumLabel?.text = self.objects[indexPath.item]

    cell.backgroundColor = UIColor(r: 51, b: 51, g: 51)
    return cell

But it results in empty labels on my cells. My cell label is returning nil but everything looks connected between my xib and collectionviewcell subclass.

Here are the xib-code file connections:

enter image description here

and the custom cell class:

import UIKit

class AlbumCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var albumImage: UIImageView!
    @IBOutlet weak var albumLabel: UILabel?

1 answer

  • answered 2018-07-11 05:03 Ashish Kanani

    check delegate and dataSource protocol of collectionView is connected or not ? if not then add this code in viewDidLoad() method

    collectionView.delegate = self
    collectionView.dataSource = self