Wednesday 20 August 2014

UICollectionViewCell Selection and Deselection

Problem:

Today, i ran into a problem where i wanted to do some stuff on selection and deselection of a collectionView cell.
I inserted two delegate methods in my controller namely:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath


- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

When i tapped on my collectionView cell the method didSelectItemAtIndexPath was getting called. But when i tapped on the same cell again the method didDeselectItemAtIndexPath did not get called instead didSelectRowAtIndexPath was getting called again, hence, the actions that i specified in didDeselectItemAtIndexPath were not running.


Solution:

Add    
 [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:nil]
to your didSelectItemAtIndexPath and also 

Add
 [collectionView deselectItemAtIndexPath:indexPath animated:NO]
to your  didDeselectItemAtIndexPath method to solve the problem.

After banging my head around for a while i realised that collectionView can't make out whether the cell is selected or deselected until we tell it so. Hence we tell the collectionView that we want this cell to be selected. What this does is that it makes the collectionView call the didDeselectItemAtIndexPath method the when we tap on the cell for the second time.

Additional Notes:

- Setting cell.selected = YES or NO does not solve the problem. Please try avoiding it as the Apple Documentation also says that "The preferred way to select the cell and highlight it is to use the selection methods of the collection view object."

1 comment:

  1. Can you please give a code snippet,i am not able to understand how to add [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:nil]
    to our didSelectItemAtIndexpath.

    ReplyDelete