2012-12-28 37 views
1

我發現了幾個相關的問題,例如this,但我仍然需要一些幫助。 我想要的是一個按鈕,一旦點擊,按以下任一方式隨機飛行: 1,它飛過五個隨機位置並飛回原位。或 2,它隨機飛行2秒,然後回到原來的位置。如何循環動畫幾次或幾秒鐘?

這裏是我的代碼,而是停止控制人仍下落不明:

//if the button clicked 
    [self animationLoop:@"Wrong!" finished:1 context:nil]; 
    -(void)animationLoop:(NSString *)animationID finished:(int)finished context:(void *)context { 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:1]; 
    [UIView setAnimationRepeatCount:finished]; 

    CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width); 
    CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height); 
    CGPoint squarePostion = CGPointMake(x, y); 
    theWrongButton.center = squarePostion; 

    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)]; 

    [UIView commitAnimations]; 
    } 

我想我的問題是有點像幾十倍或幾秒鐘如何循環動畫。

回答

0

我終於用這樣的:

//in the animation loop 
     if (animationLoopCounter > 3) { 
     return; 
     } 

    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:)]; 

    - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { 
    animationLoopCounter++; 
    [self animationLoop:@"Wrong!" finished:1 context:nil]; 
    } 
1

您所要求的正是上下文參數的用途。它使您能夠傳入任何可以稍後使用的對象。例如,一些像這樣的是什麼,你可能會尋找:

[self animationLoop:@"Wrong!" finished:1 context:[NSNumber numberWithInt:0]]; 
-(void)animationLoop:(NSString *)animationID finished:(int)finished context:(void *)context { 

    NSNumber *count = (NSNumber *)context; 
    if ([count intValue]) >= 5) { 
     return; 
    } 
    [UIView beginAnimations:nil context:[NSNumber numberWithInt:[count intValue]+1]]; 
    [UIView setAnimationDuration:1]; 
    [UIView setAnimationRepeatCount:finished]; 

    CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width); 
    CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height); 
    CGPoint squarePostion = CGPointMake(x, y); 
    theWrongButton.center = squarePostion; 

    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)]; 

    [UIView commitAnimations]; 
    } 
+0

我需要算++的地方?謝謝。 –

+0

其在'...上下文中:[NSNumber numberWithInt:[count intValue] +1]' –

0

試試這個

[UIView animateWithDuration:<#(NSTimeInterval)#> 
        animations:<#^(void)animations#> 
        completion:<#^(BOOL finished)completion#>]; 

這個動畫命令帶有一個完成塊。