18

我想在插入和/或刪除UICollectionViewCell時自定義動畫樣式。UICollectionView動畫(插入/刪除項目)

我需要這個的原因是,默認情況下,我看到插入一個單元在動畫中有一個平滑的淡入淡出,但是刪除一個單元有一個向左移動+淡出動畫的組合。如果不是因爲一個問題,我會非常高興。

當我刪除一個單元格時,它在添加新單元格時仍然可以重用,並且在重用時它不會添加默認的淡入淡出效果,而是向左移動+淡入。

我不確定爲什麼我在動畫中出現這種不一致。如果這是一個已知的bug /問題/愚蠢(在我身邊),請讓我知道如何解決它。

否則,請告訴我如何在單元格被刪除時設置自定義動畫(或指向我的教程)。

感謝

UPDATE

通過繼承UICollectionViewFlowLayout和添加的代碼

- (UICollectionViewLayoutAttributes *) initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath { 

     return nil; 
} 

這就是它這條線固定怪異的動畫行爲! :)

回答

24

如果您使用自己的UICollectionViewLayout子類,可以實現方法:

  • initialLayoutAttributesForAppearingItemAtIndexPath:用於插入

  • finalLayoutAttributesForDisappearingItemAtIndexPath:的缺失

根據文檔,您返回的屬性將用作動畫的起點,並且終點是標準由佈局返回的al屬性(或相反的刪除)。佈局屬性包括位置,alpha,轉換... 當然,編寫自己的佈局類比使用Apple提供的流佈局要花更多功夫。

編輯:爲了在評論中回答你的問題,這裏是一個佈局的超級基本實現,所有行的大小相同。

單元格有一個frame,默認情況下,alpha爲1.0(如layoutAttributesForItemAtIndexPath:所定義)。刪除時,其屬性將從刪除前的當前狀態到由finalLayoutAttributesForDisappearingItemAtIndexPath:設置的屬性設置爲動畫,這些屬性對應於相同的framealpha爲0.0。所以它不會移動,但會淡出。但是,右側的單元格將被移動到左側(因爲它們的indexPath已更改,因此它們的framelayoutAttributesForItemAtIndexPath:設置)。

- (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; 
} 
+0

謝謝紀堯姆。但是,你能給我一個具體的例子嗎?比方說,我想確保我的單元格在被刪除時只是淡出,我如何在自定義的UICollectionViewLayout中實現該單元格? –

+0

我在回答你的問題時添加了一個例子。 – Guillaume

5

下載circle Layout。這是一個示例自定義佈局,使用

initialLayoutAttributesForAppearingItemAtIndexPath: 
finalLayoutAttributesForDisappearingItemAtIndexPath: 

這將是一個很好的工作材料給你。

相關問題