Ios 如何在删除循环之前等待重复的循环完成

Ios 如何在删除循环之前等待重复的循环完成,ios,core-animation,caanimation,Ios,Core Animation,Caanimation,我有一个观点,我使用CAAnimation让脉动 CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"]; animation.values = @[ @0.0f, @1.0f, @0.0f ]; animation.duration = 0.5; animation.repeatCount = HUGE_VALF; [view.layer addAnimation:anima

我有一个观点,我使用
CAAnimation
让脉动

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
animation.values = @[ @0.0f, @1.0f, @0.0f ];
animation.duration = 0.5;
animation.repeatCount = HUGE_VALF;

[view.layer addAnimation:animation forKey:@"pulsate"];
当我使用
[view.layer removeAnimationForKey:@“pulsate”]
删除动画时,不透明度会立即恢复。我想实现的是,当前执行的脉动动画完成,然后移除动画

我尝试将
repeatCount
设置为1,但这会引发异常,因为动画是不可变的

我还尝试从表示层获取当前值并将其应用于模型,然后删除动画并再次添加动画以完成它。但这会在停止动画时出现明显的打嗝,而且计时通常是关闭的


有没有一种方法可以让动画完成一个循环,然后将其删除?

有很多细节需要纠正,但一般的想法是创建一个在完成时删除的非重复动画,然后使用
animationDidStop
委托方法重新启动动画

- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag
{
    NSString *animationIdentifier = [animation valueForKey:@"AnimationIdentifier"];

    if ( [animationIdentifier isEqualToString:@"PulseAnimation"] )
    {
        if ( self.pulseActive )
            [self.orangeView2.layer addAnimation:self.pulseAnimation forKey:@"pulsate"];
    }
}
第一件事是申报一些财产

@property (weak, nonatomic) IBOutlet UIImageView *orangeView2;
@property (nonatomic) bool pulseActive;
@property (strong, nonatomic) CAKeyframeAnimation *pulseAnimation;
第一个属性是将设置动画的视图,第二个属性跟踪动画是否已启用,最后一个属性是实际动画(存储在属性中,因此我们只需实例化一次)

接下来,我们将使用惰性实例化来创建动画对象

- (CAKeyframeAnimation *)pulseAnimation
{
    if ( !_pulseAnimation )
    {
        _pulseAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
        _pulseAnimation.values = @[ @0.0f, @1.0f, @0.0f ];
        _pulseAnimation.duration = 0.5;

        _pulseAnimation.delegate = self;
        [_pulseAnimation setValue:@"PulseAnimation" forKey:@"AnimationIdentifier"];
    }

    return( _pulseAnimation );
}
这里最重要的是

  • 动画不会重复(默认情况下)
  • 动画是
    removedOnCompletion
    (默认情况下)
  • 委托
    被设置为
    self
    ,以便
    animationDidStop
    方法 将被称为
  • 使用
    setValue:forKey:
仅当多个动画使用同一代理时才需要最后一项,因为在这种情况下,您需要一种方法来确定哪个动画称为
animationDidStop
。传递给
forKey
setValue
的字符串是任意的,存储在动画对象的字典中

好的,现在我们需要实现
animationDidStop
。实现将检查
pulseActive
属性,并在必要时重新启动动画(在检查动画的标识后)

剩下的就是开始和停止动画。例如,用于切换动画的按钮

- (IBAction)pulseButtonPressed
{
    if ( !self.pulseActive )
    {
        self.pulseActive = YES;
        [self.orangeView2.layer addAnimation:[self pulseAnimation] forKey:@"pulsate"];
    }
    else
    {
        self.pulseActive = NO;
    }
}

对我来说,重用动画并没有像预期的那样有效,但是添加一个新的动画效果非常好。谢谢