UICollectionView 添加/删除动画

要实现UICollectionView在添加或删除一项是放大缩小动画。

  1. 自定义UICollectionViewFlowLayout
    创建子类MyChosenFlowLayout 继承自 UICollectionViewFlowLayout
#import <UIKit/UIKit.h>

@interface MyChosenFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) NSInteger addAnimatedIndex;
@property (nonatomic, assign) NSInteger removeAnimatedIndex;

@end
#import "MyProductChosenFlowLayout.h"

@implementation MyChosenFlowLayout

// 添加时动画
- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath {
    UICollectionViewLayoutAttributes *attributes = [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];
    if (self.addAnimatedIndex == itemIndexPath.row) {
        attributes.transform = CGAffineTransformMakeScale(0.0, 0.0);
        attributes.alpha = 0;
    }else {
        attributes.alpha = 1;
    }
    return attributes;
}

//删除时动画
- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath *)itemIndexPath {
    UICollectionViewLayoutAttributes *attributes = [super finalLayoutAttributesForDisappearingItemAtIndexPath:itemIndexPath];
    if (self.removeAnimatedIndex == itemIndexPath.row) {
        attributes.transform = CGAffineTransformMakeScale(0.1, 0.1);
        attributes.alpha = 0;
    }
    return attributes;
}

@end

2.设置UICollectionView的 collectionViewLayout

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        self.flowLayout = [[MyChosenFlowLayout alloc] init];
        self.flowLayout.addAnimatedIndex = -1;
        self.flowLayout.removeAnimatedIndex = -1;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = self.backgroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [_collectionView registerClass:[MyChosenCell class] forCellWithReuseIdentifier:@"MyChosenCell"];
        _collectionView.scrollEnabled = NO;
    }
    return _collectionView;
}
  1. 添加一项到末尾
    NSIndexPath *addIndexPath = [NSIndexPath indexPathForRow:[self.items count] inSection:0];
    self.flowLayout.addAnimatedIndex = [self.items count];
    [self.items insertObject:item atIndex:[self.functionItems count]];
    [self.collectionView insertItemsAtIndexPaths:@[addIndexPath]];
    self.flowLayout.addAnimatedIndex = -1;

4.删除 row = index 项,对应的数据是item

        self.flowLayout.removeAnimatedIndex = index;
        [self.items removeObject:item];
        [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]];
        self.flowLayout.removeAnimatedIndex = -1;
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页