如何取消UIView旋转块动画

时间:2013-07-16 15:41:45

标签: ios animation uiview block

- (void)viewDidLoad
 {
[super viewDidLoad];
label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 50)];
label.layer.cornerRadius = 5.0f;
label.text = @"hello world";
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
[label release];
[self startAnimation];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 60, 30);
[btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}

- (void)startAnimation
{
 CGAffineTransform transForm = CGAffineTransformMakeRotation(angel * M_PI/180.0f);
[UIView animateWithDuration:0.1f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^(void){
    label.transform = transForm;
} completion:^(BOOL finished) {
    NSLog(@"1");
    angel = angel + 5;
    [self startAnimation];
}];
}

 - (void)btnPressed:(id)sender
 {
  //method 1 :[label.layer removeAllAnimations];   not work...
//method 2 : CGAffineTransform transForm = CGAffineTransformMakeRotation(M_PI/180.0f);
//label.transform = transForm;      not work...
}

我旋转标签,现在我要取消它,我搜索了网站上可能存在的问题,并找到了两个解决方案,我试过了,但这两个解决方案不起作用..

1 个答案:

答案 0 :(得分:1)

使用[label.layer removeAllAnimations]时动画不会停止,因为无论[self startAnimation]变量的值如何,都会调用finished。即使您取消动画,这也会导致动画继续。

您应该将动画完成块更改为以下内容:

- (void)startAnimation
{
  CGAffineTransform transForm = CGAffineTransformMakeRotation(angel * M_PI/180.0f);
  [UIView animateWithDuration:0.1f delay:0.0f options:UIViewAnimationOptionCurveLinear     animations:^(void){
    label.transform = transForm;
  } completion:^(BOOL finished) {
    if (finished) {
      NSLog(@"1");
      angel = angel + 5;
      [self startAnimation];
    }
  }];
}

[label.layer removeAllAnimations]

中使用btnPressed