使用BOOL /完成块停止自动反转/无限重复UIView动画

Luk*_*uke 24 core-animation objective-c uiviewanimation ios completion-block

我正在设置以下UIView animateWithDuration:方法,目的是animationOn在程序中的其他位置设置我的BOOL以取消无限循环重复.我的印象completion是每次动画循环结束时都会调用该块,但事实并非如此.

是否completion在重复动画中调用了块?如果没有,是否有另一种方法可以在此方法之外停止此动画?

- (void) animateFirst: (UIButton *) button
{
    button.transform = CGAffineTransformMakeScale(1.1, 1.1);
    [UIView animateWithDuration: 0.4
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                     animations: ^{
                         button.transform = CGAffineTransformIdentity;
                     } completion: ^(BOOL finished){
                         if (!animationOn) {
                             [UIView setAnimationRepeatCount: 0];
                         }
    }];
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ren 51

只有在动画中断时才会调用完成块.例如,当应用程序进入后台并再次返回前台时(通过多任务处理),它会被调用.在这种情况下,动画停止.发生这种情况时应该重新启动动画.

要停止动画,您可以从视图的图层中删除它:

[button.layer removeAllAnimations];
Run Code Online (Sandbox Code Playgroud)

  • @TomvanZummeren 但这将删除每个动画.... 如果您有多个动画块并且只想停止其中一个动画块怎么办.... (2认同)

Rec*_*eel 9

旧但另一种选择.

您还可以设置另一个不在同一视图上重复的动画,这样您也可以在当前状态下捕获它并使用选项UIViewAnimationOptionBeginFromCurrentState将其返回到它的状态.您的完成块也被调用.

-(void)someEventSoStop
{
    button.transform = CGAffineTransformMakeScale(1.0, 1.0);
    [UIView animateWithDuration: 0.4
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                     animations: ^{
                         button.transform = CGAffineTransformIdentity;
                     } completion: ^(BOOL finished){

                     }];
}
Run Code Online (Sandbox Code Playgroud)