Wednesday, June 12, 2013

CAAnimation removedOnCompletion example in Objective C (iOS).

CAAnimation removedOnCompletion

Determines if the animation is removed from the target layer’s animations upon completion.

@property(getter=isRemovedOnCompletion) BOOL removedOnCompletion

Discussion of [CAAnimation removedOnCompletion]
When YES, the animation is removed from the target layer’s animations once its active duration has passed. Defaults to YES.

CAAnimation removedOnCompletion example.
rota.removedOnCompletion = NO;
That should leave the presentation layer where it was when the animation finished. The default is YES, which will snap back to the model value, i.e., the behavior you describe.

The fillMode should also be set, i.e.,

rota.fillMode = kCAFillModeForwards;

Example of [CAAnimation removedOnCompletion].
They cause the presentation to be preserved at the end of the animation.

animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;

Then the "animationDidStop:" method can be used to remove the view at the end of the animation:

-(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag {
    if (animation == [containerView.layer animationForKey:@"moveX"]) {
        // remove view here, add another view and/or start another transition
    }
}

CAAnimation removedOnCompletion example.
An example would be

CABasicAnimation *scaleX = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
//this is not used, as the group provides the duration
scaleX.duration = duration;
scaleX.autoreverses = NO;

scaleX.toValue = [NSNumber numberWithFloat:1.0];
scaleX.fromValue = [NSNumber numberWithFloat:scaleFrom];
scaleX.fillMode = kCAFillModeForwards;
scaleX.removedOnCompletion = NO;

CABasicAnimation *scaleY = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
//this is not used, as the group provides the duration
scaleY.duration = duration;
scaleY.autoreverses = NO;

scaleY.toValue = [NSNumber numberWithFloat:1.0];
scaleY.fromValue = [NSNumber numberWithFloat:scaleFrom];
scaleY.fillMode = kCAFillModeForwards;
scaleY.removedOnCompletion = NO;

//add in the translation animations

NSMutableArray* animationsArray = [NSMutableArray arrayWithObjects:scaleX,
                                                                   scaleY,
//and any other animations you want in the group
                                       nil];

CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.duration = 1.0/2;
animationGroup.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseIn];
animationGroup.animations = animationsArray;
animationGroup.delegate = self;
animationGroup.removedOnCompletion = YES;
animationGroup.fillMode = kCAFillModeForwards;
[animationGroup setValue:@"imageTransform" forKey:@"AnimationName"];
[b.layer addAnimation:animationGroup forKey:@"imageTransform"];

End of CAAnimation removedOnCompletion example article.