2012-08-30 164 views
0

我想要做的是以編程方式在屏幕左上角創建一個UIView矩形,然後將其移到右上角,右下角,左下角,最後回到左上角。但它不能按預期工作。我的代碼有什麼問題?爲什麼UIView動畫不起作用

#import "ViewController.h" 

@interface ViewController() 
@property (nonatomic,strong) UIView *myView; 
@end 

@implementation ViewController 
@synthesize myView = _myView; 


- (IBAction)animation:(UIButton *)sender { 
    [UIView animateWithDuration:3.0 animations:^{ 
     self.myView.alpha = 0.75; 
     self.myView.frame = CGRectMake(160, 0, 160,230);}]; 

    [UIView animateWithDuration:3.0 animations:^{ 
     self.myView.alpha = 0.50; 
     self.myView.frame = CGRectMake(160, 230, 160,230);}]; 

    [UIView animateWithDuration:3.0 animations:^{ 
    self.myView.alpha = 0.25; 
    self.myView.frame = CGRectMake(0, 230, 160,230);}]; 

    [UIView animateWithDuration:3.0 animations:^{ 
    self.myView.alpha = 0.00; 
    self.myView.frame = CGRectMake(0, 0, 160,230);} 
    completion:^(BOOL finished) { 
    [self.myView removeFromSuperview]; 
    }]; 

} 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    CGRect viewRect = CGRectMake(0, 0, 160, 230); 
    UIView *mv = [[UIView alloc] initWithFrame:viewRect]; 
    self.myView = mv; 
    self.myView.backgroundColor = [UIColor redColor]; 
    [self.view addSubview:self.myView]; 

} 
@end 

編輯: 我修復嵌套完成塊的問題:

- (IBAction)animation:(UIButton *)sender { 
    [UIView animateWithDuration:3.0 animations:^{ 
     self.myView.alpha = 0.75; 
     self.myView.frame = CGRectMake(160, 0, 160,230);} 
    completion:^(BOOL finished) { 
     [UIView animateWithDuration:3.0 animations:^{ 
      self.myView.alpha = 0.50; 
      self.myView.frame = CGRectMake(160, 230, 160,230);} 
      completion:^(BOOL finished) { 
       [UIView animateWithDuration:3.0 animations:^{ 
        self.myView.alpha = 0.25; 
        self.myView.frame = CGRectMake(0, 230, 160,230);} 
      completion:^(BOOL finished) { 
       [UIView animateWithDuration:3.0 animations:^{ 
        self.myView.alpha = 0.00; 
        self.myView.frame = CGRectMake(0, 0, 160,230);} 
           completion:^(BOOL finished) { 
            [self.myView removeFromSuperview]; 
      }];}];}];}];} 

但它是可怕的閱讀。有沒有其他方法?

+0

嘗試_after_當前部分是啓動動畫的下一部分完成,不與它平行。可憐的'UIView'不能決定它應該做什麼。 :) – holex

+0

聽起來有趣..你能更具體,並把代碼在答案? – Philip007

回答

0

這不是特定的動畫,但你應該嘗試這種模式,使動畫部分彼此順序後再次啓動:

[UIView animateWithDuration:3.0 animations:^{ 
    // first part of the animation 
} completion:^(BOOL finished) { 
    [UIView animateWithDuration:3.0 animations:^{ 
     // second part of animation 
    } completion:^(BOOL finished) { 
     [UIView animateWithDuration:3.0 animations:^{ 
      // third part of the animation 
     } completion:^(BOOL finished) { 
      [UIView animateWithDuration:3.0 animations:^{ 
       // forth part of the animation 
      } completion:^(BOOL finished) { 
       // finish and clear the animation 
      }]; 
     }]; 
    }]; 
}]; 
+0

握手。我剛剛發現一樣。但嵌套塊看起來很醜。任何其他方式? – Philip007

+0

你可以在沒有完成選擇塊的情況下製作塊,但Apple強烈建議在iOS4 +中使用基於塊的動畫。 – holex