I have a UICollectionView
and I implemented collectionView(_:didSelectItemAt:)
and collectionView(_:didDeselectItemAt:)
. When I scroll to the bottom of the collection view and select it, I want it to stay selected, so I don't call collectionView(_:didDeselectItemAt:)
in collectionView(_:didSelectItemAt:)
. Now, the problem is that when I scroll from the selected cell at the bottom to the cell at the top, the app crashes unexpectedly found nil while unwrapping an Optional value
. My guts tell me this has to do with the dequeueing of cells under the hood.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ServiceMenuItemCell
cell.backgroundColor = UIColor(colorLiteralRed: 0/255.0, green: 138/255.0, blue: 217/255.0, alpha: 1.0)
UIView.animate(withDuration: 0.1, animations: {
cell.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}, completion: { finish in
UIView.animate(withDuration: 0.05, animations: {
cell.transform = CGAffineTransform.identity
})
})
}
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ServiceMenuItemCell
cell.backgroundColor = UIColor(colorLiteralRed: 177/255.0, green: 179/255.0, blue: 181/255.0, alpha: 1.0)
}
How can I solve this correctly?