HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Consecutive animations

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
animationsconsecutivestackoverflow

Problem

I'm new to Core Animations, I want to fade out two different layers one after another.I write them in a CATransaction block. I wonder if there is better approach to make such animations.

[CATransaction begin];

    CABasicAnimation *fadeOutLoadingBar = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutLoadingBar.fromValue = [NSNumber numberWithFloat:0.3];
    fadeOutLoadingBar.toValue = [NSNumber numberWithFloat:0.];
    fadeOutLoadingBar.fillMode = kCAFillModeForwards;
    fadeOutLoadingBar.beginTime = [_loadingLayer convertTime:CACurrentMediaTime() fromLayer:nil];
    fadeOutLoadingBar.duration = .8;
    fadeOutLoadingBar.removedOnCompletion = NO;
    [_loadingLayer addAnimation:fadeOutLoadingBar forKey:nil];

    [self setupCheckMarkLayer]; //initialize _checkMarkLayer 
    CABasicAnimation *fadeOutCheckMark = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutCheckMark.fromValue = [NSNumber numberWithFloat:0.3];
    fadeOutCheckMark.toValue = [NSNumber numberWithFloat:0.];
    fadeOutCheckMark.fillMode = kCAFillModeForwards;
    fadeOutCheckMark.beginTime = [_checkMarkLayer convertTime:CACurrentMediaTime() fromLayer:nil] + 0.5;
    fadeOutCheckMark.duration = 1.0;
    fadeOutCheckMark.removedOnCompletion = NO;
    _checkMarkLayer.opacity = 0.;
    [_checkMarkLayer addAnimation:fadeOutCheckMark forKey:nil];

    [CATransaction setCompletionBlock:^{
        self.userInteractionEnabled = YES;
        [self.delegate finishedLoading];
        [self setupLoadingLayer];
    }];

    [CATransaction commit];

Solution

We have some magic numbers. Also, why don't we use modern syntax for our NSNumber objects?

NSNumber *opacityFromValue = @0.3f;
NSNumber *opacityToValue = @0.0f;

CGFloat fadeLoadBarDuration = 0.8;
CGFloat fadeCheckmarkDuration = 1.0;

CGFloat timeCheckmarkOffset = 0.5;


And now use these variables in place of the magic numbers.

As an added bonus, we'll get slightly better performance by not having to instantiate the opacity values twice each. NSNumber is an immutable object, so it doesn't matter that we pass the same one both times.

Code Snippets

NSNumber *opacityFromValue = @0.3f;
NSNumber *opacityToValue = @0.0f;

CGFloat fadeLoadBarDuration = 0.8;
CGFloat fadeCheckmarkDuration = 1.0;

CGFloat timeCheckmarkOffset = 0.5;

Context

StackExchange Code Review Q#69735, answer score: 3

Revisions (0)

No revisions yet.