2013-07-16 82 views
1

如何取消UIView的旋轉塊動畫

- (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... 
} 

我旋轉的標籤,現在我想取消它,我搜索的網站可能的問題,並發現了大約兩個解決方案,我試過了,但是這兩個解決方案不起作用。

+0

您還可以旋轉回相同的角度。例如:如果你旋轉180度,然後再旋轉-180 ..:P – HDdeveloper

回答

1

當您使用[label.layer removeAllAnimations]時,動畫不會停止,因爲無論finished變量的值是多少,都會調用[self startAnimation]。即使您取消了動畫,這也會導致動畫繼續。

您應該在動畫完成塊更改爲以下:

- (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

+0

是的,它工作。謝謝!我打印出「完成」布爾值,當我按下按鈕時,它是0。完成「。文檔如下所示:」動畫序列結束時要執行的塊對象,該塊沒有返回值,並且只有一個布爾參數,指示在調用完成處理程序之前動畫是否實際完成。如果動畫的持續時間爲0,則在下一個運行循環開始時執行該塊,該參數可能爲NULL。我認爲removeAllAnimations操作會完成動畫 – frank