在Tap上动画UICollectionViewCell

its*_*e69 12 core-animation ios6 uicollectionview uicollectionviewcell

UICollectionViewCell当用户点击一个单元格时,我想开始一些动画.我的想法是选择相应的单元格didSelectItemAtIndexPath并触发动画.但是,这不起作用:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// animate the cell user tapped on
ProductCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductReuseID" forIndexPath:indexPath];

[UIView animateWithDuration:5.0
                      delay:0
                    options:(UIViewAnimationOptionAllowUserInteraction)
                 animations:^{
                     NSLog(@"animation start");
                     [cell.layer setBackgroundColor:[UIColor colorWithRed: 180.0/255.0 green: 238.0/255.0 blue:180.0/255.0 alpha: 1.0].CGColor];
                 }
                 completion:^(BOOL finished){
                     NSLog(@"animation end");
                     [cell.layer setBackgroundColor:[UIColor whiteColor].CGColor];
                 }
 ];
}
Run Code Online (Sandbox Code Playgroud)

实际上,动画同时开始和结束(尽管animateWithDuration设置为5).下一次尝试是跳过动画并简单地设置一个不同的边框样式:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// animate the cell user tapped on
ProductCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductReuseID" forIndexPath:indexPath];

[cell.layer setBorderWidth:5.0f];
}
Run Code Online (Sandbox Code Playgroud)

但是,这并没有改变任何东西(可能是因为我必须手动重绘单元格?).

你有任何想法如何在用户点击它时动画UICollectionViewCell吗?

亲切的问候,基督徒

Kev*_*ers 33

你似乎得到了错误的Cell.发送所述dequeueReusableCellWithReuseIdentifier:forIndexPath:消息中获得在在第二参数的indexPath视图使用电池,但取出一个先前使用的可重复使用的,但细胞; 如果没有可重用的单元可用,则创建一个新单元.见下面的参考文献1.

更换:

ProductCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductReuseID" forIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

附:

ProductCollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,应该为您提供合适的单元格.

这是你的第一个例子,重写.

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath(NSIndexPath *)indexPath
{
    // animate the cell user tapped on
    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];    
    [UIView animateWithDuration:5.0
            delay:0
            options:(UIViewAnimationOptionAllowUserInteraction)
                animations:^{
                    NSLog(@"animation start");
                    [cell setBackgroundColor:[UIColor colorWithRed: 180.0/255.0 green: 238.0/255.0 blue:180.0/255.0 alpha: 1.0]];
                }
                completion:^(BOOL finished){
                    NSLog(@"animation end");
                    [cell setBackgroundColor:[UIColor whiteColor]];
                }
    ];
}
Run Code Online (Sandbox Code Playgroud)

参考文献: