Yassin
Yassin

Reputation: 1059

Value of type 'UICollectionViewCell' has no member 'imageView'

I'm setting up a new project with a UICollectionView that displays an image. I created the ViewController and the CellViewController, just like its supposed to.

In the CellViewController the code is the following:

import UIKit

class ClubCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
}

But in the ViewController when I'm setting up the image it gives me the error. Here's the code:

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


    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                      for: indexPath)
    // Configure the cell
    cell.backgroundColor = UIColor.black
    cell.imageView.image = UIImage(named: "pic1")
    return cell;
}

Thanks in advance..

Upvotes: 1

Views: 6656

Answers (1)

dirtydanee
dirtydanee

Reputation: 6151

You should cast your collectionViewCell subclass as your custom one ClubCollectionViewCell.

Use guard to check for the type of the cell, do fatalError() if it fails.

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

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                            for: indexPath) as? ClubCollectionViewCell else {
                                                                    fatalError("Wrong cell class dequeued")
    }
        // Configure the cell
        cell.backgroundColor = UIColor.black
        cell.imageView.image = UIImage(named: "pic1")
        return cell
 }

Upvotes: 2

Related Questions