ios 删除所有动画不起作用



我有一个永远的动画,但我想在某个时候停止它,我尝试删除所有动画,但它不起作用。这是我的代码。

[self.backgroundImageView.layer removeAllAnimations];
-(void)animateToLeft{
    if(isInCenter){
        [UIView animateWithDuration:10.0f animations:^{
            backgroundImageView.frame = CGRectMake(kLeftX, 0, kBackgroundWidth, kBackgroundHeight);
        }completion:^(BOOL finished) {
            [self animateToRight];
        }];
         isInCenter = NO;
    }
    else{
        [UIView animateWithDuration:20.0f animations:^{
            backgroundImageView.frame = CGRectMake(kLeftX, 0, kBackgroundWidth, kBackgroundHeight);
        }completion:^(BOOL finished) {
            [self animateToRight];
        }];
    }
}
-(void)animateToRight{
    [UIView animateWithDuration:20.0f animations:^{
        backgroundImageView.frame = CGRectMake(kRightX, 0, kBackgroundWidth, kBackgroundHeight);
    }completion:^(BOOL finished) {
        [self animateToLeft];
    }];
}

这在您的情况下不起作用。

因为[self.backgroundImageView.layer removeAllAnimations];这将删除已添加的所有图层动画[self.backgroundImageView.layer addAnimation:/*CABasicAnimation should added here*/];

您可以通过在完成时设置布尔变量来停止此循环,然后使用布尔变量进行检查。

使用布尔值,如果设置了该值,则不要执行下一个动画 - 同时取消挂起的动画。

例如

@interface MyClass () {
     BOOL cancelAll;
}
@implementation MyClass
-(void)cancelAnimation {
     self.imageView.layer removeAllAnimations]; //!
     cancelAll = YES;
}
-(void)animateToLeft{
        if(cancelAll)
            return;
        ...
}
-(void)animateToRight{
        if(cancelAll)
            return;
        ...
}

最新更新