I am trying to show the selected cell in my UICollectionView
by changing its border and shadow color. my issue is that my DidDeselect
function causes a crash if I select a cell then scroll the selected cell of screen and select another cell, I understand that is because my DidDeselect
is trying to deselect a cell that has been reused so my question is:
How do I remove the border from a cell that is no longer visible once it has scrolled off the screen
My DidSelect
:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath as IndexPath) as! PresentationCell
cell.layer.borderColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
cell.layer.borderWidth = 3
cell.layer.shadowColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
}
My DidDeSelect
:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cellItem = collectionView.cellForItem(at: indexPath) as! PresentationCell
cellItem.layer.borderColor = UIColor.clear.cgColor
cellItem.layer.borderWidth = 3
cellItem.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}
It crashes on this line:
let cellItem = collectionView.cellForItem(at: indexPath) as! PresentationCell
Error is : Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Which I understand is because the cell I selected first is no longer displayed because I've scrolled it out of view and then selected a cell at the bottom of the collectionView
How do I get around this?