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

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

4

3 回答 3

1

您要问的正是 context 参数的用途。它使您可以传入以后可以使用的任何对象。例如,您可能正在寻找像这样的一些:

    [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];
   }
于 2012-12-28T00:21:16.583 回答
0

试试这个

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

这个动画命令带有一个完成块。

于 2012-12-28T00:21:53.497 回答
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];
   }
于 2012-12-28T00:49:04.047 回答