Search code examples
ios7uicollectionviewcelluiviewanimationalpha

Best way to animate visiblity of UICollectionViewCell in iOS7+


I need to animate the visibility of UICollectionViewCells on startup such that they are visible randomly when my application launches. But since I already have the items to be displayed they are visible at the same time. I tried below solution & it works correctly. But I want to know the best & optimized way to achieve this task

- (void)animateCollectionViewCellsVisiblity
{
    // First set alpha to 0
    for (NSUInteger i = 0; i< self.dataArray.count; i++)
    {
        [self applyAlpha:0.0 toItem:i inSection:0];
    }

    // Initially collectionview is hidden while fetching data, so show it now
    self.collectionView.hidden = NO;

    // Now set alpha to 1 with a random delay
    for (NSUInteger i = 0; i< self.dataArray.count; i++)
    {
        CGFloat delay = [self randomNumberWithlowerBound:0 upperBound:self.dataArray.count] + 0.05;
        [UIView animateWithDuration:.2 delay:delay options:UIViewAnimationOptionCurveEaseIn animations:^{
            [self applyAlpha:1.0 toItem:i inSection:0];
        } completion:nil];
    }
}

- (void)applyAlpha:(CGFloat)alpha toItem:(NSInteger)item inSection:(NSInteger)section
{
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:section]];
    cell.alpha = alpha;
}

- (int)randomNumberWithlowerBound:(int)lowerBound upperBound:(int)upperBound
{
    int randomValue = arc4random_uniform(upperBound - lowerBound + 1) + lowerBound;
    return randomValue;
}

Solution

  • Your solution is great. That's how it is done. Looks pretty optimized to me.

    You could make your code shorter by dropping the section parameter which is always zero. And you possibly eliminate the applyAlpha method by adding just two lines before your animate block.