Skip to content

Instantly share code, notes, and snippets.

@stanislaw
Forked from ericallam/gist:11214298
Created September 14, 2016 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stanislaw/3e71034dc68dee774218c9e4f2c60830 to your computer and use it in GitHub Desktop.
Save stanislaw/3e71034dc68dee774218c9e4f2c60830 to your computer and use it in GitHub Desktop.
Fixing animation snapback without setDisableActions:YES
// Implements the solution for solving "snapback" found in
// Chapter 8 of "iOS Core Animation Advanced Techniques" by Nick Lockwood
// without the need to use setDisableActions: to override the implicit animation,
// instead passing in the implicit animation key in addAnimation:forKey:
// With setDisableActions
- (void)applyBasicAnimation:(CABasicAnimation *)animation toLayer:(CALayer *)layer
{
//set the from value (using presentation layer if available)
animation.fromValue = [layer.presentationLayer ?: layer valueForKeyPath:animation.keyPath];
//update the property in advance
//note: this approach will only work if toValue != nil
[CATransaction begin];
[CATransaction setDisableActions:YES];
[layer setValue:animation.toValue forKeyPath:animation.keyPath];
[CATransaction commit];
//apply animation to layer
[layer addAnimation:animation forKey:nil];
}
// Without setDisableActions
- (void)applyBasicAnimation:(CABasicAnimation *)animation toLayer:(CALayer *)layer
{
//set the from value (using presentation layer if available)
animation.fromValue = [layer.presentationLayer ?: layer valueForKeyPath:animation.keyPath];
// update the property in advance
[layer setValue:animation.toValue forKeyPath:animation.keyPath];
// Passing in the key overrides the implicit animation key for @"backgroundColor"
[layer addAnimation:animation forKey:animation.keyPath];
}
- (IBAction)changeColor
{
//create a new random color
CGFloat red = arc4random() / (CGFloat)INT_MAX;
CGFloat green = arc4random() / (CGFloat)INT_MAX;
CGFloat blue = arc4random() / (CGFloat)INT_MAX;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
//create a basic animation
CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"backgroundColor";
animation.toValue = (__bridge id)color.CGColor;
//apply animation without snap-back
[self applyBasicAnimation:animation toLayer:self.colorLayer];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment