UICollectionViewanimation(插入/删除项目)

我想在插入和/或删除UICollectionViewCell时自定义animation样式。

我需要这个的原因是,默认情况下,我看到插入一个单元格在animation中有一个平滑的淡入淡出,但删除一个单元格有一个移动到左侧的淡出animation的组合。 如果不是一个问题,我会非常高兴。

删除一个单元格后,当我添加新的单元格时它仍然会被重用,并且当它被重用时,它不会添加默认的淡入淡出效果,而是向左移动和淡入的组合。

我不知道为什么我在animation中出现这种不一致。 如果这是一个已知的bug /问题/愚蠢(在我身边),请让我知道如何解决它。

否则,请告诉我如何在单元格被删除时设置自定义animation(或指向我的教程)。

谢谢

UPDATE

通过inheritanceUICollectionViewFlowLayout并添加这行代码来修复奇怪的animation行为

- (UICollectionViewLayoutAttributes *) initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath { return nil; } 

而已! 🙂

如果您使用自己的UICollectionViewLayout子类, UICollectionViewLayout可以实现以下方法:

  • initialLayoutAttributesForAppearingItemAtIndexPath:用于插入

  • finalLayoutAttributesForDisappearingItemAtIndexPath:用于删除

根据文档,您返回的属性被用作animation的起点,而终点是您的布局返回的正常属性(或相反的删除)。 布局属性包括position,alpha,transform …当然,编写自己的布局类比使用Apple提供的stream布局要花费更多的工作。

编辑:要在评论中回答你的问题,这里是所有相同大小的行的布局超级基本实现。

一个单元格有一个frame ,默认情况下,1.0的alpha (由layoutAttributesForItemAtIndexPath:定义) layoutAttributesForItemAtIndexPath: 删除时,其属性将从删除前的当前状态到由finalLayoutAttributesForDisappearingItemAtIndexPath:设置的属性(它们对应于相同的frame和0.0的alpha设置animation。 所以它不会移动,但会淡出。 然而,右边的单元格将会被移动到左边(因为它们的indexPath已经改变,因此它们的framelayoutAttributesForItemAtIndexPath:设置layoutAttributesForItemAtIndexPath:

 - (CGSize)collectionViewContentSize { NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:0]; return CGSizeMake(numberOfItems * ITEM_WIDTH, ITEM_HEIGHT); } - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { NSUInteger index = [indexPath indexAtPosition:0]; UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; attributes.frame = CGRectMake(index * ITEM_WIDTH, 0, ITEM_WIDTH, ITEM_HEIGHT); return attributes; } - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray *attributes = [NSMutableArray new]; NSUInteger firstIndex = floorf(CGRectGetMinX(rect) / ITEM_WIDTH); NSUInteger lastIndex = ceilf(CGRectGetMaxX(rect) / ITEM_WIDTH); for (NSUInteger index = firstIndex; index <= lastIndex; index++) { NSIndexPath *indexPath = [[NSIndexPath alloc] initWithIndexes:(NSUInteger [2]){ 0, index } length:2]; [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]]; } return attributes; } - (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath]; attributes.alpha = 0.0; return attributes; } 

下载圆形布局 。 这是使用的示例自定义布局

 initialLayoutAttributesForAppearingItemAtIndexPath: finalLayoutAttributesForDisappearingItemAtIndexPath: 

这将是一个很好的工作材料给你。