I am trying to animate a custom property on a CALayer with an implicit animation:
[UIView animateWithDuration:2.0f animations:^{
self.imageView.myLayer.myProperty = 1;
}];
In -actionForKey: method I need to return the animation taking care of interpolating the values. Of course I have to tell somehow the animation how to retrieve the other parameters for the animation (i.e. the duration and the timing function).
- (id<CAAction>)actionForKey:(NSString *)event
{
if ([event isEqualToString:@"myProperty"])
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"myProperty"];
[anim setFromValue:@(self.myProperty)];
[anim setKeyPath:@"myProperty"];
return anim;
}
return [super actionForKey:event];
}
}
Any idea on how to achieve that? I tried looking for the animation in the layer properties but could not find anything interesting. I also have a problem with the layer animating since actionForKey: is called outside of animations.
I don't think you can access the duration if you use :
Other issue with your code is, the implementation of actionForKey: of UIView only returns a CAAnimation object if the code is called inside an animation block. Otherwise it returns null to turn off animation. In your implementation, you always return a CAAnimation, hence changing to that property will always be animated.
You should use this :
Then in your actionForKey: method, use
[CATransaction animationDuration]
and[CATransaction animationTimingFunction]
to retrieve the current duration and timing function.The easiest way could be onother property in the your custom layer to set before myProperty. like:
And
If you want to get parameters, like duration, set in
So in this case duration = 2.0f
you can use CATransaction and valueForKey. CATransaction should return the specific value of the context.
I reckon that you have a custom layer with you custom property "myProperty" that you added to the backing layer of UIView - according to the Documentation UIView animation blocks does not support the animation of custom layer properties and states the need to use CoreAnimation:
Further the documentation sates that UIView supports just a limited set of animatable properties which are:
https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html#//apple_ref/doc/uid/TP40009503-CH6-SW12
You have to create a CABasicAnimation for that.
You can have sort of a workaround with CATransactions if you return a CABasicAnimation in actionForKey: like that
Just change your actionForKey: method to something like that
There is something in Github in case you wan't to have a look: https://github.com/iMartinKiss/UIView-AnimatedProperty