I have a custom UICollectionViewCell subclass that overwrites initWithFrame:
and layoutSubviews
to setup its views. However, I\'m now trying to do two
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.
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
}
}
}
If you want to show animation on selection then following method might helpful to you :
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"cell #%d was selected", indexPath.row);
// animate the cell user tapped on
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
[UIView animateWithDuration:0.8
delay:0
options:(UIViewAnimationOptionAllowUserInteraction)
animations:^{
[cell setBackgroundColor:UIColorFromRGB(0x05668d)];
}
completion:^(BOOL finished){
[cell setBackgroundColor:[UIColor clearColor]];
}
];
}
In your custom UICollectionViewCell subclass you could override the setSelected:
as so:
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
if (selected) {
[self animateSelection];
} else {
[self animateDeselection];
}
}
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.
Should not mess with state when overridden in this way:
override var isSelected: Bool {
get {
return super.isSelected
}
set {
super.isSelected = newValue
.
.
.
}
}