2012-10-21 74 views
6

我在UICollectionView中顯示大量圖像單元格。 只需一個按鈕,我希望能夠將我的所有細胞分組到第一個細胞。UICollectionView:動畫自定義佈局

這是行之有效的,但是當我試圖向我的重組動作添加動畫轉換時,沒有任何反應。

在這裏,我在自定義佈局使用方法:

- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect 
{ 
    NSArray* allAttributesInRect = [super layoutAttributesForElementsInRect:rect]; 

    if([allAttributesInRect count] > 0 && _isRegroup) 
    { 
     UICollectionViewLayoutAttributes *firstAttribute = [allAttributesInRect objectAtIndex:0]; 
     CGRect frame = firstAttribute.frame; 

     for(UICollectionViewLayoutAttributes *attribute in allAttributesInRect) 
      [UIView animateWithDuration:0.3f animations:^{attribute.frame = frame;}]; 
    } 
    return allAttributesInRect; 
} 

- (void)regroupCells:(BOOL)isRegroup // This method is called from my collection controller when my button is pressed 
{ 
    _isRegroup = isRegroup; 
    [self invalidateLayout]; 
} 

任何想法? 謝謝!

回答

21

動畫將不會從您調用它們的方法中起作用。

要將佈局和動畫更改爲新佈局,最簡單的方法是在集合視圖上調用performBatchUpdates,對於每個塊參數使用nil。這會使您的佈局無效併爲您製作新的動畫。

在執行此操作之前,您會告訴佈局對象您希望新佈局發生。此外,在layoutAttributesForElementsInRect內,只需檢查您的布爾變量並將分組的幀(可能中心會更好)應用到所有屬性中,但不需要動畫。您還需要在layoutAttributesForElementAtIndexPath中重現此代碼。

因此,簡言之:

  1. 取下它是
  2. 卸下他們在哪裏動畫調用你的佈局無效的呼叫,只需修改佈局屬性
  3. 添加..forElementAtIndexPath代碼以及
  4. 在您的視圖控制器中,調用佈局對象的重組方法,然後調用集合視圖上的performBatchupdates。
+0

謝謝!我明白它是如何工作的:) – Pierre

+0

以下是希望看到的結果:) http://d.pr/v/QUTF(我有一個小故障問題) – Pierre

+0

您需要增加「top 「項目在堆棧中,您可以在調整框架的同一位置執行此操作。 – jrturton

相關問題