Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView selection does not last

I have a UICollectionView I use like a tool selection container. You have many tools (the cells), when you select one, the former selected is deselected, and so on... You can only have one tool selected at a time.

The problem is that I can't manage to have the cells selected. When I tap the cell, the collectionView:didSelectItemAtIndexPath: is called. I then reload the selected cell to change it's appearance (I change the alpha of the image) by using the [collectionView reloadItemsAtIndexPaths:@[indexPath]].

Well that reloads the cell ok, except one damn thing: in the collectionView:cellForItemAtIndexPath: the cell never get the selected property set to YES! So I can never change the alphabecause I never know when I must draw a selected cell or not.

Worse: [collectionView indexPathsForSelectedItems] is always empty!!!

I don't even mention the collectionView:didDeselectItemAtIndexPath: that is never called...

Well, if someone can help me understand what is going on, thanks in advance...

like image 788
Zaphod Avatar asked Dec 05 '25 14:12

Zaphod


1 Answers

When you call reloadItemsAtIndexPaths: the collection view discards those cells and creates new ones, therefor discarding the selected state of the cells.

I'd suggest a couple of different options:

1.) In collectionView:didSelectItemAtIndexPath: call cellForItemAtIndexPath: to get a reference to the selected cell and update it's appearance there.

2.) (My Favorite) Use a custom subclass of UICollectionViewCell if you're not already, and override the method setSelected:. There you'll be notified when the cell is selected and you can update the appearance from within the subclass.

like image 90
dalton_c Avatar answered Dec 08 '25 06:12

dalton_c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!