块动画立即完成,但CABasicAnimation与自定义动画属性一起正常工作

时间:2014-10-16 21:52:00

标签: ios objective-c animation objective-c-blocks caanimation

有很多相关的问题,但现有问题似乎没有解决这种情况。

我创建了一个包含自定义图层的视图,以便可以为其中一个属性设置动画。使用CABasicAnimation类,动画可以正常工作。

但是,我需要对动画进行更多控制,例如轻松和缓出以及顺序动画,并尝试切换到使用块动画。但是,当我这样做时,动画立即完成,而不是随着时间的推移动画。

如何让这个块动画正常工作?

工作动画代码:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"inputValue"];
animation.duration = DEFAULT_ANIMATION_DURATION;

if (flipped) {
    animation.fromValue = [NSNumber numberWithDouble:0.0];
    animation.toValue = [NSNumber numberWithDouble:1.0];
    self.myLayer.inputValue = 1.0;
} else {
    animation.fromValue = [NSNumber numberWithDouble:1.0];
    animation.toValue = [NSNumber numberWithDouble:0.0];
    self.myLayer.inputValue = 0.0;
}

[self.layer addAnimation:animation forKey:@"animateInputValue"];

立即错误完成的动画,但finished为YES:

[UIView animateWithDuration:10.0 delay:0.0 options:0 animations:^{
    self.myLayer.inputValue = 1.0;
} completion:^(BOOL finished) {
    NSLog(@"done %@", finished?@"and finished":@", but not finished");
}];

动画CALayer:

#import "UViewLayer.h"
#import "YoYouStyleKit.h"

@implementation UViewLayer

+ (BOOL)needsDisplayForKey:(NSString *)key {
    if( [key isEqualToString:@"inputValue"] )
        return YES;
    return [super needsDisplayForKey:key];
}

- (void)setInputValue:(CGFloat)inputValue {
    _inputValue = inputValue;
    [self setNeedsDisplay];
}

- (void)drawInContext:(CGContextRef)context {
    UIGraphicsPushContext(context);
    [YoYouStyleKit drawUShapeWithFrame:self.bounds input:self.inputValue];
    UIGraphicsPopContext();
}

在自定义图层中添加@dynamic inputValue;似乎没有任何区别。

2 个答案:

答案 0 :(得分:1)

不要混合UIKit和Core Animation动画。

像这样实施:

[CATransaction begin];

[CATransaction setCompletionBlock:^
{
    NSLog(@"done");
}];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"inputValue"];
animation.duration = DEFAULT_ANIMATION_DURATION;

if (flipped)
{
    animation.fromValue = [NSNumber numberWithDouble:0.0];
    animation.toValue = [NSNumber numberWithDouble:1.0];
    self.myLayer.inputValue = 1.0;
} 
else 
{
    animation.fromValue = [NSNumber numberWithDouble:1.0];
    animation.toValue = [NSNumber numberWithDouble:0.0];
    self.myLayer.inputValue = 0.0;
}

[self.layer addAnimation:animation forKey:@"animateInputValue"];

[CATransaction commit];

答案 1 :(得分:1)

除了Leo Natan的回答,如Apple docs中所述:

  

自定义图层对象忽略基于视图的动画块参数和   请改用默认的Core Animation参数。

更简单的是,如果您更改了animatable properties之一,则可以为UIView自己的图层属性设置动画。

对于图层inputValue等自定义属性,您可以在图层(id<CAAction>)actionForKey:(NSString *)key中提供CABasicAnimation,但不会使用UIView动画参数(持续时间...)。

当您更改UIView块动画中的图层属性时,将播放此动画,但只有在您设置值时,它才会播放。

Leo Natan提供的代码是最容易从UIView动画图层的代码。

相关问题