UICollectionView在旋转时重新排列单元格

时间:2013-04-29 13:49:22

标签: ios6 uicollectionview evernote uicollectionviewlayout

我希望在设备旋转期间重新排列UICollectionView个单元格,方法与evernote iPads app中的注释类似。在默认实现中,只有细胞的淡入和淡出,但我希望细胞在旋转过程中移动。

实现类似动画的推荐方法是什么?我是否需要创建自定义UICollectionViewLayout

1 个答案:

答案 0 :(得分:1)

我设法通过继承UICollectionViewFlowLayout并覆盖两个方法来获得所需的旋转效果:initialLayoutAttributesForAppearingItemAtIndexPathfinalLayoutAttributesForDisappearingItemAtIndexPath这两个控制点分别定义了起始/最终布局要插入到集合视图中的项目的信息。

参见源代码:

<强>·H

#import "UICollectionView.h"

@interface UITestCollectionViewFlowLayout : UICollectionViewFlowLayout
@end

<强>的.m:

#import "UITestCollectionViewFlowLayout.h"

@interface UITestCollectionViewFlowLayout () 
{
    BOOL _isRotating; 
}

@property (strong, nonatomic) NSIndexPath* lastDissappearingItemIndex;

@end

@implementation UITestCollectionViewFlowLayout

@synthesize lastDissappearingItemIndex = _lastDissappearingItemIndex;

// returns the starting layout information for an item being inserted into the collection view
- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
{

    UICollectionViewLayoutAttributes* attributes = (UICollectionViewLayoutAttributes *)[self layoutAttributesForItemAtIndexPath:itemIndexPath];

    if (_isRotating) // we want to customize the cells layout only during the rotation event
    {
        if ([self.lastDissappearingItemIndex isEqual:itemIndexPath])
            return nil; // do not animate appearing cell for the one that just dissapear
        else
        {
            attributes.alpha = 0;

            // setting the alpha to the new cells that didn't match the ones dissapearing is not enough to not see them so we offset them
            attributes.center =  CGPointMake(attributes.center.x, attributes.size.height * 2 + attributes.center.y);
        }

    }

    return attributes;
}

// returns the final layout information for an item that is about to be removed from the collection view
- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath*)itemIndexPath
{

    UICollectionViewLayoutAttributes* attributes = (UICollectionViewLayoutAttributes *)[self layoutAttributesForItemAtIndexPath:itemIndexPath];

    if (_isRotating)
    {
        attributes.alpha = 1.0;

        self.lastDissappearingItemIndex = itemIndexPath;
    }

    return attributes;
}

- (void) viewController:(UIViewController *)viewController didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    _isRotating = NO;
}

- (void) viewController:(UIViewController *)viewController willRotateToInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration
{
    _isRotating = YES;
}

请注意,我正在使用我从viewcontroller设置的标志,该标志创建此flowlayout以了解我们何时实际旋转;原因是我希望这种效果只在旋转期间发生。

我很想听听有关此代码的反馈/改进。