How can I customize the selection state of my UICollectionViewCell subclass?

ios, iphone, objective-c, uicollectionview, uicollectionviewcell

Solution

Add a public method `performSelectionAnimations` to the definition of `MyCollectionViewCell` that changes the desired `UIImageView` and performs the desired animation. Then call it from `collectionView:didSelectItemAtIndexPath:`.

So in MyCollectionViewCell.m:

- (void)performSelectionAnimations {
    // Swap the UIImageView
    ...

    // Light bounce animation
    ...
}

And in your `UICollectionViewController`:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell performSelectionAnimations];
}

Notice I've taken out the call to `[cell setSelected:YES]`, since that should already be taken care of by the UICollectionView. From the documentation:

The preferred way to select the cell and highlight it is to use the selection methods of the collection view object.

Problem

I have a custom UICollectionViewCell subclass that overwrites `initWithFrame:` and `layoutSubviews` to setup its views. However, I'm now trying to do two things which I'm having trouble with. 1) I'm trying to customize the state of the `UICollectionViewCell` upon selection. For example, I want to change one of the images in an `UIImageView` in the `UICollectionViewCell`. 2) I want to animate (light bounce) the `UIImage` in the `UICollectionViewCell`. Can anyone point me in the right direction? ``` - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]; [cell setSelected:YES]; } ```

Original source