2013-01-24 39 views
3

我想在iOS中使用animateWithDuration:方法制作動畫。添加隨機性來循環UIView動畫塊

我在屏幕上移動一個圖像(UIImageView中的雲的簡單圖片),然後使該動畫在循環中運行,並且每次穿過屏幕時都要更改速度(持續時間)。

我已經嘗試了一些方法,但都表現不正確的我。

我第一次,雖然我可以用UIViewAnimationOptionRepeat這樣的:

[UIImageView animateWithDuration:arc4random() % 10 + 1 
          delay:0.0 
         options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionRepeat 
         animations:^{ 
//moving the cloud across the screen here 
} 
completion:^(BOOL finished) { 
    NSLog(@"Done!"); 
}]; 

但是,這似乎並沒有再次調用arc4random()重置時間...即。只有在每次啓動應用程序時,雲纔會以隨機速度穿過屏幕,而不是每次動畫循環時。

我然後使用完畢塊火動畫再次嘗試這樣的:

-(void)animateMethod 
{ 
[UIImageView animateWithDuration:arc4random() % 10 + 1 
          delay:0.0 
         options:UIViewAnimationOptionCurveLinear 
         animations:^{ 
//moving the cloud across the screen here 
} 
completion:^(BOOL finished) { 
    NSLog(@"Done!"); 
    [self animateMethod]; 
}]; 
} 

這給了我,我要找的效果,但是當我推到另一個視圖使用導航控制器完成塊被解僱似乎無盡的循環(我的日誌得到垃圾郵件與「完成!」)

任何人都知道的方式來獲得所需的效果我想正確的方式?

回答

5

你在正確的軌道上。關鍵在於如果動畫完成失敗,您只需循環。所以你需要在告訴它循環之前檢查finishedBOOL是否爲真。

-(void)animateMethod 
{ 
    [UIImageView animateWithDuration:arc4random() % 10 + 1 
           delay:0.0 
          options:UIViewAnimationOptionCurveLinear 
          animations:^{ 
    //moving the cloud across the screen here 
    } 
    completion:^(BOOL finished) { 
     if (finished) { 
      NSLog(@"Done!"); 
      [self animateMethod]; 
     } 
    }]; 
} 

這種方法能很好的完成非常簡單的動畫,這樣,當你只是做了幾個,像在一個時間,也許3-5雲。除此之外,您可能需要使用NSTimer或CADisplayLink設置自己的動畫循環,並調整其中的雲框。它是一個更爲人工的方式,但它會爲你帶來一些很好的動畫,即使在UIKit中也是如此。

+0

是的,這解決了我的問題..我知道我是在正確的軌道上。我剛開始學習iOS的動畫,所以感謝NSTimer和CADisplayLink的提示。 –

+0

沒問題。快樂編碼:) –