我想在插入和/或删除 UICollectionViewCell 时自定义动画样式。
我需要这个的原因是,默认情况下,我看到插入单元格的动画具有平滑的淡入淡出效果,但是删除单元格具有向左移动+淡出动画的组合。如果不是因为一个问题,我会对此感到非常高兴。
删除单元格后,当我添加新单元格时,它仍然会被重复使用,并且当它被重复使用时,它的添加不会使用默认的淡入效果,而是左移+淡入的组合。
我不确定为什么动画中会出现这种不一致的情况。如果这是一个已知的错误/问题/愚蠢(在我这边:))请让我知道如何修复它。
否则,请让我知道如何在删除单元格时设置自定义动画(或向我指出教程)。
Thanks
UPDATE
通过子类化 UICollectionViewFlowLayout 并添加这行代码修复了奇怪的动画行为
- (UICollectionViewLayoutAttributes *) initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath {
return nil;
}
就是这样! :)
如果您使用自己的子类UICollectionViewLayout
,您可以实现以下方法:
根据文档,您返回的属性用作动画的起点,终点是布局返回的普通属性(或删除时相反)。布局属性包括位置、alpha、变换……
当然,编写自己的布局类比使用Apple提供的流布局需要更多的工作。
编辑:为了回答您在评论中的问题,这里是大小相同的项目行布局的超级基本实现。
一个细胞有一个frame
并且,默认情况下,alpha
1.0(定义为layoutAttributesForItemAtIndexPath:
)。当它被删除时,它的属性将从删除前的当前状态动画到由finalLayoutAttributesForDisappearingItemAtIndexPath:
,对应相同的frame
and an alpha
0.0。所以它不会移动,但会淡出。然而,右侧的单元格将被移动到左侧(因为它们的indexPath
已经改变,因此他们的frame
由设置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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)