App crashes when I deselect an item in a UICollectionView

194 views Asked by At

I'm working on UICollectionView. I'm assigning one image to collection view cell when user selects it, and changing the image when user selects other cell, as shown in below code

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

    let selectedCell : CollectionCellForAlertView = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionCellForAlertView
    println("cell selected")
    selectedCell.imageView.image = UIImage(named: "someImage.png")

}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath){
    println("deselected")
    let deselectedCell : CollectionCellForAlertView = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionCellForAlertView
    deselectedCell.imageView.image = UIImage(named: "someOtherImage.png")

}

Sometimes it works properly but some other times it crashes because 'deselectedCell' will have nil value. Can anybody please tel me how to resolve this.

1

There are 1 answers

2
RandomBytes On

I think this might work for you. I tested it in my app and it worked.

     let deselectedCell = collectionView.cellForItemAtIndexPath(indexPath) as CollectionCellForAlertView
        deselectedCell.imageView.image = UIImage(named: "someOtherImage.png")