UICollectionView : 动画自定义布局 [英] UICollectionView : animation custom layout

查看:42
本文介绍了UICollectionView : 动画自定义布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UICollectionView 中显示了许多图像单元格.通过一个按钮,我希望能够将我的所有单元格分组到第一个按钮上.

I'm displaying lots of image cells in an UICollectionView. With one button I would like to be able to group all my cell over the first one.

这运行良好,但是当我尝试将动画过渡添加到我的重组动作时,没有任何反应.

This is working well but when I'm trying to add an animation transition to my regroup action, nothing happens.

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

Here the method I use in a custom layout :

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

有什么想法吗?谢谢!

推荐答案

动画在你调用它们的方法中不起作用.

Animations won't work from within the method you are calling them from.

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

To change the layout and animate to a new one, the simplest method is to call performBatchUpdates on your collection view, with nil for each block parameter. This invalidates your layout and animates to the new one for you.

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

Before doing this, you'd tell the layout object that you want the new layout to occur. Also, inside layoutAttributesForElementsInRect, simply check your Boolean variable and apply the grouped frame (probably center would be better) to all attributes as you are doing now, but without animation. You'll also need to reproduce this code in layoutAttributesForElementAtIndexPath.

所以,总结一下:

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

这篇关于UICollectionView : 动画自定义布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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