在UICollectionView中设置所有UICollectionViewCell的动画

时间:2012-12-03 20:10:17

标签: ios uicollectionview

我想知道在UICollectionView中动画所有单元格的好方法是什么。我正在尝试在UICollectionView中模拟编辑。所以我想要做的是收缩UICollectionViewCells的所有边界。所以我拥有的是:

- (IBAction)startEditingMode:(id)sender {
    [_items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];

        [UIView animateWithDuration:0.25 animations:^{
            cell.layer.transform = CATransform3DMakeScale(0.9, 0.9, 1);
        }];
    }];
}

它有效,但我不确定UICollectionView上是否有属性,或者更好的标准方法来执行此类操作。感谢。

2 个答案:

答案 0 :(得分:1)

我会创建一个UICollectionViewLayout子类。添加名为editing的BOOL属性。编辑更改时,请调用invalidateLayout。然后在-layoutAttributesForItemAtIndexPath:方法返回的属性中,您可以指定转换。

您的方法存在的问题是它只影响可见细胞。 UICollectionViewLayout子类很好,因为即使添加了新的单元格,它也会将变换应用于所有单元格。它将所有集合视图布局处理移出视图控制器。

单元属性可以包括框架,大小,中心,变换(3D),alpha和您自己的自定义属性。

您将更改-performBatchUpdates:block中的编辑值,如wL _所示。

- (IBAction)startEditingMode:(id)sender {
    [self.collectionView performBatchUpdates:^{
        ((MyCollectionViewLayout *)self.collectionView.collectionViewLayout).editing = YES;
    }
    completion:NULL];
}

在UICollectionViewLayout子类中:

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

    if (self.editing) {
        attributes.transform = CGAffineTransformMakeScale(0.9, 0.9);
    }
    else {
        attributes.transform = CGAffineTransformIdentity;
    }

    return attributes;
}

另请注意,您(可能)此处不需要3D转换。仿射变换就足够了。

答案 1 :(得分:0)

您是否尝试过使用UICollectionView performBatchUpdates:

类似的东西:

[collectionView performBatchUpdates:^{
    [_items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
        cell.layer.transform = CATransform3DMakeScale(0.9, 0.9, 1);
    }];
} completion:^{}];