您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

小技巧:如何干掉 UICollectionView 的隱式動畫

編輯:iOS 開發基礎

作者:裡脊串(授權本站轉載)

調用 reloadItemsAtIndexPaths: 時,UICollectionView 預設會附帶一個淡入淡出(fade)的隱式動畫。平時感覺不明顯,但當 cell 是複合 cell 時就很惱人——比如 cell 內部用到了 UIStackView。

下面三種寫法都能把這段動畫去掉:

// 方法一
[UIView performWithoutAnimation:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];

// 方法二
[UIView animateWithDuration:0 animations:^{
    [collectionView performBatchUpdates:^{
        [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    } completion:nil];
}];

// 方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
    [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
    [UIView setAnimationsEnabled:YES];
}];

如果你的 App 只支持 iOS 7 及以上,推薦直接用第一種 performWithoutAnimation:(感謝 @sunnyxx 提供的 tip),簡單又乾脆。

But——問題還沒結束。

上面幾招只能屏蔽 UIView 層級的動畫。一旦 cell 裡還藏著 CALayer 的動畫,它們就無能為力了,例如下面這種在 layoutSubviews 中同步子 layer frame 的寫法:

- (void)layoutSubviews {
    [super layoutSubviews];

    self.frameLayer.frame = self.frameView.bounds;
}

這種情況多見於自定義控件裡使用了 layer.mask 的場景。解法也很簡單,用 CATransaction 把隱式動畫關掉即可:

- (void)layoutSubviews {
    [super layoutSubviews];

    [CATransaction begin];
    [CATransaction setDisableActions:YES];

    self.frameLayer.frame = self.frameView.bounds;

    [CATransaction commit];
}

Done!

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved