Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while selecting and deselecting rows in collectionview

I have a problem when I quickly selecting and deselecting rows in my collectionView. I have a map and above it i have a horizontal collectionView that i choose what i want to see.

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

        let selectedCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
        selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
        switch indexPath.row {
        case 0:
            query0()
            break
        case 1:
            query1()
            break
        case 2:
            query2()
            break
        case 3:
            query3()
            break
        default:

            break
        }

    }

and the code for deselecting is:

 func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cellToDeselect:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
        cellToDeselect.contentView.backgroundColor = UIColor.clearColor()
    }

The error i get is this:

fatal error: unexpectedly found nil while unwrapping an Optional value

When i tried to selecting slowly the cells i didn't get the error But if i do it quickly it crashes

I commented the deselect function and i didn't get any errors (and i check it with quick change of cells)

like image 229
mike vorisis Avatar asked Mar 04 '26 07:03

mike vorisis


2 Answers

Instead of changing color in didSelect and didDeSelect try something like this

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
     let view = UIView(frame: cell.contentView.bounds)
     view.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
     cell.selectedBackgroundView = view
}

Hope this will help you.

like image 58
Nirav D Avatar answered Mar 05 '26 22:03

Nirav D


Your app is crashing Because you are getting nil when you access invisible cell using

 let cellToDeselect:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!

Make cellToDeselect varible as optional & use optional chaining while changing color.

Replace your code with this

let cellToDeselect:UICollectionViewCell? = collectionView.cellForItemAtIndexPath(indexPath)?
        cellToDeselect?.contentView.backgroundColor = UIColor.clearColor()
like image 26
Rohit Pradhan Avatar answered Mar 05 '26 21:03

Rohit Pradhan