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

前端 未结 5 1986
再見小時候
再見小時候 2021-02-01 04:02

I have a custom UICollectionViewCell subclass that overwrites initWithFrame: and layoutSubviews to setup its views. However, I\'m now trying to do two

5条回答
  •  猫巷女王i
    2021-02-01 04:23

    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.

提交回复
热议问题