user10423812
user10423812

Reputation:

Unable to edit the reusable collection view cell

I am trying something like this:

let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as! PostAttachmentCellView 
cell.backgroundImage.image = file as? UIImage

here collectionView has reusable cells of type PostAttachmentCellView.

However it throws an error of:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

the population is done in this way:

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

    return cell
}

I don't understand what's wrong here and how I should correct this. Help is much appreciated.

I don't want to just remove the error by putting it in let but I want the cell to have the background image too (as intuitive from the code).

Upvotes: 1

Views: 81

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

The cell is not nil only if it's visible

if let cell = collectionView.cellForItem(at: indexPath) as? PostAttachmentCellView {
   cell.backgroundImage.image = file as? UIImage
}

//

so you may edit the dataSource array of images and reload the table/cell

var images = [UIImage]()

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PACell", for: indexPath) as! PostAttachmentCellView
    cell.backgroundImage.image = images[indexPath.row]
    cell.customize()

    return cell
}

in your example you change image of first top cell so do this instead

 images[0] = file as? UIImage
 // here either reload the table/cell

Upvotes: 2

Related Questions