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,
and any animations you apply to the layer’s properties respect the
animation parameters of the current view-based animation block. The
same is not true for layers that you create yourself. Custom layer
objects ignore view-based animation block parameters and use the
default Core Animation parameters instead.

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

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

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

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

Table 4-1 lists the animatable properties—the properties that have
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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...