astrolka astrolka - 1 year ago 109
iOS Question

ImageView of a custom CollectionViewCell is nil when it should be configured

I have a

with a
collectionView's cells
are custom ones, they contains just a

Here is my test project

Here are
required methods from my
CollectionView class

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell

let image = UIImage(named: listItems[indexPath.row])
cell.testImageView.image = image

return cell

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listItems.count

When I try to set image for cell's imageView I get this

fatal error: unexpectedly found nil while unwrapping an Optional value

I have checked
, it isn't
, but
is, I get this error when I try to set image to collectionViewCell's testImageView.
How can I fix it?
enter image description here

Here is method called from
to fill collectionView's

func load(listItem: [String]) {
self.listItems = listItem


Also if I remove code from
collectionView cellForItemAt indexPath
with this one all is working fine

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath)
let imageView = UIImageView(image:UIImage(named: listItems[indexPath.row]))

cell.backgroundView = imageView

Answer Source

You have mistaken your two view controllers. Your IB outlet is connected to a cell in a different view controller. I mean you can have multiple views in different controllers connected to a same IBOutlet, but in your case the one that loads first is not connected, so that is why it crashes.

This is the cell your outlet was connected to. This is the cell your outlet was connected to.

This is that you are trying to load (but did not connect IBOutlet to image view):

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download