如何自定义 UICollectionViewCell 子类的选择状态? [英] How can I customize the selection state of my UICollectionViewCell subclass?

查看:28
本文介绍了如何自定义 UICollectionViewCell 子类的选择状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义 UICollectionViewCell 子类,它覆盖 initWithFrame:layoutSubviews 以设置其视图.但是,我现在正在尝试做两件我遇到麻烦的事情.

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) 我正在尝试在选择时自定义 UICollectionViewCell 的状态.例如,我想在 UICollectionViewCell 中更改 UIImageView 中的一张图像.

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) 我想为 UICollectionViewCell 中的 UIImage 设置动画(光反弹).

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

推荐答案

MyCollectionViewCell 的定义中添加一个公共方法 performSelectionAnimations 来更改所需的 UIImageView 并执行所需的动画.然后从 collectionView:didSelectItemAtIndexPath: 调用它.

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:.

所以在 MyCollectionViewCell.m 中:

So in MyCollectionViewCell.m:

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

    // Light bounce animation
    ...
}

在你的 UICollectionViewController 中:

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

请注意,我已经取消了对 [cell setSelected:YES] 的调用,因为 UICollectionView 应该已经处理了这个问题.来自文档:

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.

这篇关于如何自定义 UICollectionViewCell 子类的选择状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆