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];
}
Add a public method
performSelectionAnimations
to the definition ofMyCollectionViewCell
that changes the desiredUIImageView
and performs the desired animation. Then call it fromcollectionView:didSelectItemAtIndexPath:
.So in MyCollectionViewCell.m:
And in your
UICollectionViewController
: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:If you want to show animation on selection then following method might helpful to you :
In your custom UICollectionViewCell subclass you could override the
setSelected:
as so:I have found that on repeated touches this method is called on a cell even if it's already selected so you may want to just check that you are really changing state before firing unwanted animations.
In your custom
UICollectionViewCell
subclass, you can implementdidSet
on theisSelected
property.Swift 3:
Swift 2: