astrolka astrolka - 1 month ago 13
iOS Question

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

I have a

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

Here is my test project

Here are
DataSource
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
error
:


fatal error: unexpectedly found nil while unwrapping an Optional value


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

Here is method called from
tableViewController
to fill collectionView's
listItem


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

}


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

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

Comments