CAKeyframeAnimation: content changes to the first image when stopped

I am updating the contents of a CALayer using the following code:

 CAKeyframeAnimation *countanimation = [CAKeyframeAnimation animation]; NSArray *images = [NSArray arrayWithObjects:(id)[UIImage imageNamed:@"number3"].CGImage, (id)[UIImage imageNamed:@"number2"].CGImage, (id)[UIImage imageNamed:@"number1"].CGImage, nil]; [countanimation setKeyPath:@"contents"]; [countanimation setValues:images]; [countanimation setCalculationMode:kCAAnimationDiscrete]; [countanimation setDuration:3.0f]; [countanimation setDelegate:self]; [countanimation setAutoreverses:NO]; [countanimation setRemovedOnCompletion:NO]; [countanimation setValue:@"Countdown" forKey:@"name"]; [countDown addAnimation:countanimation forKey:nil]; 

And want to hide the layer when the animation is stopped:

 - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { if([[anim valueForKey:@"name"] isEqual:@"Countdown"]) { [countDown setHidden:YES]; ... } } 

The problem is that the layer blinks once with the original image (number 3) and hides after that.

I want to know why the layer goes back to the original, even if I set removedOnCompletion to NO .

+4
source share
4 answers

I replaced the original image with number1, and the problem was resolved.

0
source

You can use the FillMode property in combination with the removedOnCompletion property to return the first frame back to its contents after repeatCount completed.

 [countanimation setFillMode:kCAFillModeBoth]; [countanimation setRemovedOnCompletion:NO]; 

I think that these two lines of code can help you get the desired result.

+5
source

I used animation.fillMode = kCAFillModeForwards; to fix this problem.

+1
source

Swift 4 + 5

Update Jami's answer for Swift 4 and 5

 colorAnimation.fillMode = .both colorAnimation.isRemovedOnCompletion = false 
0
source

All Articles