ios – 如何在使用隐式动画为CALayer设置动画时继承动画属性

前端之家收集整理的这篇文章主要介绍了ios – 如何在使用隐式动画为CALayer设置动画时继承动画属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用隐式动画在CALayer上设置自定义属性的动画:
[UIView animateWithDuration:2.0f animations:^{
    self.imageView.myLayer.myProperty = 1;
}];

在-actionForKey:方法我需要返回动画,负责插值.当然,我必须以某种方式告诉动画如何检索动画的其他参数(即持续时间和计时功能).

- (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];
    }
}

有关如何实现这一点的任何想法?我尝试在图层属性中查找动画,但找不到任何有趣的内容.我也对图层动画有问题,因为actionForKey:在动画之外调用.

解决方法

我估计你有一个自定义属性,你自定义属性“myProperty”,你添加到UIView的支持层 – 根据文档UIView动画块不支持自定义图层属性的动画,并声明需要使用CoreAnimation:

Changing a view-owned layer is the same as changing the view itself,@H_403_16@ and any animations you apply to the layer’s properties respect the@H_403_16@ animation parameters of the current view-based animation block. The@H_403_16@ same is not true for layers that you create yourself. Custom layer@H_403_16@ objects ignore view-based animation block parameters and use the@H_403_16@ default Core Animation parameters instead.

If you want to customize the animation parameters for layers you@H_403_16@ create,you must use Core Animation directly.

此外,文档声称UIView仅支持一组有限的可动画属性@H_403_16@哪个是:

>框架@H_403_16@>界限@H_403_16@>中心@H_403_16@>变换@H_403_16@>阿尔法@H_403_16@> backgroundColor@H_403_16@> contentStretch

Views support a basic set of animations that cover many common tasks.@H_403_16@ For example,you can animate changes to properties of views or use@H_403_16@ transition animations to replace one set of views with another.

Table 4-1 lists the animatable properties—the properties that have@H_403_16@ built-in animation support—of the UIView class.

https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html#//apple_ref/doc/uid/TP40009503-CH6-SW12

你必须为此创建一个CABasicAnimation.

如果在actionForKey中返回CABasicAnimation,则可以使用CATransactions进行某种解决方法:就像那样

[UIView animateWithDuration:duration animations:^{
    [CATransaction begin];
    [CATransaction setAnimationDuration:duration];

    customLayer.myProperty = 1000; //whatever your property takes

    [CATransaction commit];
  }];

只需将actionForKey:方法更改为类似的方法即可

- (id<CAAction>)actionForKey:(NSString *)event
{
    if ([event isEqualToString:@"myProperty"])
    {
        return [CABasicAnimation animationWithKeyPath:event];
    }
    return [super actionForKey:event];
 }

Github有一些东西,如果你不想看看:https://github.com/iMartinKiss/UIView-AnimatedProperty

猜你在找的iOS相关文章