UICollectionView:动画自定义布局

Pie*_*rre 6 layout animation ios uicollectionview

我在UICollectionView中显示了很多图像单元格.只需一个按钮,我就可以将所有细胞分组到第一个细胞上.

这很好用但是当我试图将动画过渡添加到我的重新组合动作时,没有任何反应.

这是我在自定义布局中使用的方法:

- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray* allAttributesInRect = [super layoutAttributesForElementsInRect:rect];

    if([allAttributesInRect count] > 0 && _isRegroup)
    {
        UICollectionViewLayoutAttributes *firstAttribute = [allAttributesInRect objectAtIndex:0];
        CGRect frame = firstAttribute.frame;

        for(UICollectionViewLayoutAttributes *attribute in allAttributesInRect)
            [UIView animateWithDuration:0.3f animations:^{attribute.frame = frame;}];
    }
    return allAttributesInRect;
}

- (void)regroupCells:(BOOL)isRegroup // This method is called from my collection controller when my button is pressed
{
    _isRegroup = isRegroup;
    [self invalidateLayout];
}
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?谢谢 !

jrt*_*ton 22

动画将无法在您调用它们的方法中起作用.

要更改布局并将动画更改为新布局,最简单的方法是调用performBatchUpdates集合视图,并nil为每个块参数调用.这会使您的布局和动画无效.

在执行此操作之前,您将告诉布局对象您希望新布局发生.此外,在内部layoutAttributesForElementsInRect,只需检查您的布尔变量并将分组的帧(可能是中心会更好)应用于您现在正在执行的所有属性,但没有动画.您还需要重现此代码layoutAttributesForElementAtIndexPath.

所以,总结一下:

  1. 从您所在的位置删除无效的布局调用
  2. 从它们所在的位置删除动画调用,只需修改布局属性即可
  3. 添加..forElementAtIndexPath代码
  4. 在视图控制器中,在布局对象上调用regroup方法,然后在集合视图上调用performBatchupdates.