Zaphod
Zaphod

Reputation: 7290

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...

Upvotes: 3

Views: 3452

Answers (2)

Hadi
Hadi

Reputation: 181

With regards to selecting multiple cell at once, you should try the allowsMultipleSelection property [myCollectionView setAllowsMultipleSelection:YES] The docs for that are here: https://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionView_class/Reference/Reference.html#//apple_ref/occ/instp/UICollectionView/allowsMultipleSelection

Otherwise, @daltonclaybrook's answer is sufficient.

Upvotes: 0

dalton_c
dalton_c

Reputation: 7170

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.

Upvotes: 7

Related Questions