如何循环动画几次或几秒?

时间:2012-12-28 00:12:12

标签: ios animation loops time

我发现了一些相关的问题,例如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];
  }

我认为我的问题有点像如何循环动画几次或几秒钟。

3 个答案:

答案 0 :(得分: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];
   }

答案 1 :(得分:0)

尝试这个

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

此动画命令附带一个完成块。

答案 2 :(得分: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];
   }