我如何定制我的UICollectionViewCell子类的select状态?
我有一个自定义的UICollectionViewCell子类覆盖initWithFrame:
和layoutSubviews
设置其视图。 但是,我现在正在尝试做两件事情,我遇到了麻烦。
1)我试图在select时自定义UICollectionViewCell
的状态。 例如,我想更改UICollectionViewCell
中的UIImageView
中的一个图像。
2)我想animation( UICollectionViewCell
)在UICollectionViewCell
的UIImage
。
任何人都可以指向正确的方向吗?
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]; [cell setSelected:YES]; }
将公共方法performSelectionAnimations
添加到MyCollectionViewCell
的定义中,该定义更改所需的UIImageView
并执行所需的animation。 然后从collectionView:didSelectItemAtIndexPath:
调用它。
所以在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处理了。 从文档:
select单元格并突出显示它的首选方法是使用集合视图对象的select方法。
在您的自定义UICollectionViewCell子类中,您可以覆盖setSelected:
如下所示:
- (void)setSelected:(BOOL)selected { [super setSelected:selected]; if (selected) { [self animateSelection]; } else { [self animateDeselection]; } }
我已经发现,反复触摸这个方法被调用的单元格,即使它已经被选中,所以你可能只想检查,你是真正改变状态之前发射不需要的animation。
在您的自定义UICollectionViewCell
子类中,您可以在isSelected
属性上实现didSet
。
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 } } }
如果您想在select中显示animation,则以下方法可能对您有所帮助:
- (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]]; } ]; }