Avoid animation of UICollectionView after reloadItemsAtIndexPaths

后端 未结 9 1825
情深已故
情深已故 2020-12-04 06:07

UICollectionView animate items after reloadItemsAtIndexPaths is called (fade animation).

Is there a way to avoid this animation?

iOS 6

相关标签:
9条回答
  • 2020-12-04 06:25
     func reloadRowsWithoutAnimation(at indexPaths: [IndexPath]) {
            let contentOffset = collectionView.contentOffset
            UIView.setAnimationsEnabled(false)
            collectionView.performBatchUpdates {
                collectionView.reloadItems(at: indexPaths)
            }
            UIView.setAnimationsEnabled(true)
            collectionView.setContentOffset(contentOffset, animated: false)
        }
    
    0 讨论(0)
  • 2020-12-04 06:27

    You could also try this:

    UICollectionView *collectionView;
    

    ...

    [UIView setAnimationsEnabled:NO];
    
    [collectionView performBatchUpdates:^{
        [collectionView reloadItemsAtIndexPaths:indexPaths];
    } completion:^(BOOL finished) {
        [UIView setAnimationsEnabled:YES];
    }];
    

    Edit:

    I have also found that if you wrap performBatchUpdates in a UIView animation block, the UIView animation is used instead of the default animation, so you can just set the animation duration to 0, like so:

    [UIView animateWithDuration:0 animations:^{
        [collectionView performBatchUpdates:^{
            [collectionView reloadItemsAtIndexPaths:indexPaths];
        } completion:nil];
    }];
    

    This is extra cool if you want to use iOS 7 springy animations during inserts and deletes!

    0 讨论(0)
  • 2020-12-04 06:30

    Just to add my $0.02, I tried both versions of the selected answer, and the original way worked better for my purposes. I am working on an infinite scrolling calendar view that allows for a user to enter the calendar at a given week and then swipe back and forth and select individual days for filtering a list.

    In my implementation, in order to keep things performant on older devices the array of dates that represent the calendar view has to be kept relatively small which means holding about 5 weeks worth of dates, with the user in the middle at the 3rd week. The issue with using the second approach is, there's a second step where you have to scroll the collection view back to the middle without an animation, which makes for a very jagged appearance for some reason with the blocked base animation.

    My Code:

    [UIView setAnimationsEnabled:NO];
    [self.collectionView performBatchUpdates:^{
        [self.collectionView deleteItemsAtIndexPaths:indexPathDeleteArray];
        [self.collectionView insertItemsAtIndexPaths:indexPathAddArray];
    
    } completion:NULL];
    [UIView setAnimationsEnabled:YES];
    
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:14 inSection:0];
    [self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    0 讨论(0)
提交回复
热议问题