Search code examples
objective-cxcodecore-animationcaanimation

CABasicAnimation stopping before it started?


I need to fade in my CALayers. Here's my code:

    for(int i = 0; i < viewArray.count; i++)
    {
        CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:@"opacity"];
        fadeIn.duration = 0.3;
        fadeIn.beginTime = i;
        fadeIn.fromValue = [NSNumber numberWithFloat:0.0];
        fadeIn.toValue = [NSNumber numberWithFloat:0.8];
        fadeIn.removedOnCompletion = NO;
        fadeIn.delegate = self;
        [((CALayer*)[viewArray objectAtIndex:i]) addAnimation:fadeIn forKey:nil];
    }

However, only the first two objects properly fades, all other objects do not fade at all. I've noticed that when I put a breakpoint at animationDidStop, most of the animations that have not started already stopped (even the animations that are supposed to start 60 seconds in are stopped within the first couple of seconds). I'm not exactly sure what's going on. I can see it properly when I manually set each CALayer's opacity to 1 but not when animating.


Solution

  • You are starting all of the animations at the same time, because the call to addAnimation:forKey: does not synchronously wait until the animation is complete.

    I have checked it and it seems you have to set the beginTime in a following way

    fadeIn.beginTime = CACurrentMediaTime() + i;