Synchronise all animations on collection-view cells

39 Views Asked by At

I am working on a project where I need to animate certain collection view cell background color to a flashing state. I am using the code below on my collectionviewcell subclass:

- (void) fadeInAnimation{

    if (!self.animationRunning) {
        if ([self canRunAnimation]) {
            typeof(self) __weak weakSelf = self;
            self.nameLabel.textColor = [UIColor blackColor];
            self.animationRunning = true;
            [UIView animateWithDuration:1.0
                                  delay:0.0
                                options: UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction animations:^{

                self.backgroundColor = [self.backgroundColor colorWithAlphaComponent:1.0];

            }
                             completion:^(BOOL finished) {
                [weakSelf fadeOutAnimation];
             }];
        }
        else {
            [self.layer removeAllAnimations];
            self.backgroundColor = [self.backgroundColor colorWithAlphaComponent:1.0];
        }
    }
}

- (void) fadeOutAnimation {
    typeof(self) __weak weakSelf = self;
    [UIView animateWithDuration:1.0
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction animations:^{

        self.backgroundColor = [self.backgroundColor colorWithAlphaComponent:0.65];

    }
                     completion:^(BOOL finished) {
        weakSelf.animationRunning = NO;
        [weakSelf fadeInAnimation];

     }];
}

My problem is that even though this code works, I think it is not very efficient and needs cleaning up. Also what I need, is that, all animations currently running should be synchronised in flashing however my code makes cells fade in and out in different times. I have a refresh method that refreshes UI based on the results on my API call every few seconds. Any ideas how I could synchronise currently running UIAnimations? I hope I have been clear in my question.

1

There are 1 best solutions below

0
Nelly v On

I fixed my problem by going through my view's subviews and capturing all collectionview cells on my multiple subviews and once I had them, I set their background color with alpha component gradually.. here's part of my solution inspired by Armand's answer in this question: Animation UITableViewCell backgroundcolor

- (void) animateCellFromView:(UIView*)subview {
    if ([subview isKindOfClass:[PageCollectionItemCell class]]) {
        PageCollectionItemCell *cell = (PageCollectionItemCell*)subview;
        if ([cell canRunAnimation]) {
            cell.backgroundColor = [cell.backgroundColor colorWithAlphaComponent:self.alpha];
        }
    }
}