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

user594161 picture user594161 · Dec 1, 2012 · Viewed 36.1k times · Source

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];
}

Answer

Mike Sprague picture Mike Sprague · May 11, 2015

In your custom UICollectionViewCell subclass, you can implement didSet on the isSelected property.

Swift 3:

override var isSelected: Bool {
    didSet {
        if isSelected {
            // animate selection
        } else {
            // animate deselection
        }
    }
}

Swift 2:

override var selected: Bool {
    didSet {
        if self.selected {
            // animate selection
        } else {
            // animate deselection
        }
    }
}