2013-03-04 53 views
3

我只用了一點UIView動畫和塊,基本上是一步動畫。我想將一些步驟疊加到一個序列中。下面的代碼似乎正在工作,但我想知道這是否是正確的方法和/或是否存在將塊放入塊中的任何問題/限制。正確的方式來堆疊UIView動畫和塊?

儘管代碼格式化有些笨拙/不可讀,但塊似乎很棒。

CGRect newFrame = CGRectMake(0, 0, 500, 500); 
UIView *flashView = [[UIView alloc] initWithFrame:newFrame]; 

flashView.tag = 999; 
[flashView setBackgroundColor:[UIColor grayColor]]; 
[flashView setAlpha:0.f]; 
[self.view addSubview:flashView]; 

[UIView animateWithDuration:.2f 
       animations:^{ 
        // STEP 1: FADE IN 
        [flashView setAlpha:1.f]; 
       } 
       completion:^(BOOL finished){ 
        [UIView animateWithDuration:.9f 
             animations:^{ 
              // STEP 2: FADE OUT 
              [flashView setAlpha:0.f]; 
             } 
             completion:^(BOOL finished){ 
              // STEP 3: CLEAN UP 
              [flashView removeFromSuperview]; 
             } 
         ]; 
       }]; 
+0

如果只修改一個視圖,你可以看看['CAKeyframeAnimation'](https://developer.apple.com/library /mac/documentation/GraphicsImaging/Reference/CAKeyframeAnimation_class/Introduction/Introduction.html)。 – 2013-03-04 05:30:43

回答

1

你在做什麼是正確的。有時候嵌套會變得醜陋。爲便於閱讀,一種選擇是把每個動畫在其自己的方法:

-(IBAction)someButtonPressed:(id)sender { 
    [self saveSomeData]; 
    [self fadeInAndOut]; 
} 

-(void)fadeInAndOut { 
    [UIView animateWithDuration:.2f 
        animations:^{ 
         // STEP 1: FADE IN 
         [self.flashView setAlpha:1.f]; 
        } 
        completion:[self fadeOut] 
    ]; 
} 

-(void (^)(BOOL))fadeOut { 
    return ^(BOOL finished) { 
     [UIView animateWithDuration:.9f 
         animations:^{ 
          // STEP 2: FADE OUT 
          [self.flashView setAlpha:0.f]; 
         } 
         completion:[self cleanUpFlashView] 
     ]; 
    }; 
} 

-(void (^)(BOOL))cleanUpFlashView { 
    return ^(BOOL finished){ 
     // STEP 3: CLEAN UP 
     [self.flashView removeFromSuperview]; 
    }; 
} 
1

這種方式並不可怕,如果你只是簡單的代碼嵌套一次。如果你要做更復雜的事情,你可以試試animateWithDuration:delay:options:animations:completion: 使用delay:作爲鏈接動畫的一種方法。例如:

[UIView animateWithDuration:.2f delay:0 
        options:UIViewAnimationOptionCurveEaseIn|UIViewAnimationOptionAllowUserInteraction 
       animations:^{ 
        // STEP 1: FADE IN 
        [flashView setAlpha:1.f]; 
       } 
       completion:nil 
]; 
[UIView animateWithDuration:.9f delay:.2f 
        options:UIViewAnimationOptionCurveEaseIn|UIViewAnimationOptionAllowUserInteraction 
       animations:^{ 
        // STEP 2: FADE OUT 
        [flashView setAlpha:0.f]; 
       } 
       completion:^(BOOL finished){ 
        // STEP 3: CLEAN UP 
        [flashView removeFromSuperview]; 
       } 
];