19

我正在設置以下UIView animateWithDuration:方法,目的是在程序中的其他位置設置我的animationOn BOOL以取消該無限循環重複。我的印象是,每當動畫的一個循環結束時,completion塊就會被調用,但看起來並不是這樣。使用BOOL /完成塊停止自動反向/無限重複UIView動畫

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]; 
         } 
    }]; 
} 

回答

45

完成塊只會在動畫中斷時被調用。例如,當應用程序在後臺運行並再次返回前臺時(通過多任務處理)它會被調用。在這種情況下,動畫停止。發生這種情況時應該重新開始動畫。

停止動畫,你可以從視圖的層將其刪除:

[button.layer removeAllAnimations]; 
+0

這沒有用,恐怕。應用變換後的動畫仍然在進行。 (我將'.transform'設置爲'CGAffineTransformMakeScale(1.0,1.0)')。 – Luke

+0

我發現了其他可能工作的東西。我更新了我的答案。你可以試試嗎? –

+0

哦,你自己想出來:)謝謝你接受我的答案無論如何 –

2

我已經通過調用[button.layer removeAllAnimations]解決了這個問題。

+0

我厭倦了這一點,但它對我不起作用。你從哪裏調用這個方法? – Supertecnoboff

8

舊的,但另一種選擇。

您還可以設置另一個不在同一視圖上重複的動畫,這樣您也可以在當前狀態下捕獲它,並使用選項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){ 

        }]; 
} 
+0

這是比其他解決方案更好的方法,因爲它可以順利地將動畫帶回身份。 – Nikolozi

1

作爲每個視類引用的文檔:如果使用任何類的方法,如果諸如animateWithDuration:delay:options:animations:completion: 的持續時間被設定爲負的值或0時,變化而不執行動畫製作。 所以我做了這樣的事情,停止無限循環動畫:

[UIView animateWithDuration:0.0 animations:^{ 
     button.layer.affineTransform = CGAffineTransformIdentity; 
    }]; 

我覺得這是不是刪除從該層所有動畫作爲建議的回答更好。 請注意,這適用於UIView類中的所有其他類動畫方法。

+0

這不適合我。我不得不調用removeAllAnimations。 –