1

I'm trying to create an animation in a custom class that will be triggered in an animation block like all UIView elements.

my class:

@interface SmileyFace : NSObject
@property (strong, nonatomic) uicolor* color;
@end

I'm changing color with:

[UIView animateWithDuration:3 animations:^{
            myView.frame = newFrame;
            smileyView.color = [uicolor redcolor];
        }];

Now, In the setter of the property color, I need to find out if it should be animated, and add a custom animation:

-(void)setColor:(UIColor *)color
{
    _color = color;
    NSLog(@"new frame");
    if ([CATransaction animationDuration] > 0)
        [self changeColor:color withAnimationWithDuration:[CATransaction animationDuration]];
    else
        [self changeColor:color];
}

Since my object is a custom object, I'm not sure how to access the duration of the animation. From CAtransaction, I'm always getting 0.25 as duration.

Any help will be appreciated!

1 Answers1

0

You won't get the duration from the transaction because the view isn't using a transaction to do the animations, it's using the actionForLayer:forKey delegate method to supply animations to the layer. This obviously won't work for you since your custom object isn't a view.

You could ask the view for an action for some other similar property (like backgroundColor) to see if it returns a CAAnimation in which case you can read the duration from it, or if it returns NSNull in which case you shouldn't animate. While this would work I think it is an ugly and hacky solution. (I'm not even going to show you the code because I don't want to encourage people doing so without fully understanding it (i.e. being able to write it themselves))

Since your SmileyFace isn't even a view (I do't know why you would animate something that isn't even a view), I think that it's a cleaner solution to expose a setColor:duration: method that can be used to trigger an animation if the duration is larger than 0.

CGFloat duration = 3.0;
[UIView animateWithDuration: duration animations:^{
     myView.frame = newFrame;
     [smileyView setColor:[UIColor redColor] duration:duration];
}];
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205