2012-05-07 10 views
0

私は自分自身に何度も質問してきました。のは、以下の例を見てみましょう:アニメーション化されたコード(completionBlock)とアニメーション化されていないコードの間のコードが重複しないようにする方法

if (animated) { 
    [UIView animateWithDuration:0.3 animations:^{    
     view.frame = newFrame; 
    } completion:^(BOOL finished) { 

     // same code as below 
     SEL selector = @selector(sidePanelWillStartMoving:); 
     if ([currentPanningVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
      [currentPanningVC respondsToSelector:selector]) { 
      [(id)self.currentPanningVC sidePanelWillStartMoving:self.currentPanningVC]; 
     } 

     if ([centerVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
      [centerVC respondsToSelector:selector]) { 
      [(id)centerVC sidePanelWillStartMoving:self.currentPanningVC]; 
     } 
    }]; 
} 
else { 
    view.frame = newFrame; 

    // same code as before 
    SEL selector = @selector(sidePanelWillStartMoving:); 
    if ([currentPanningVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
     [currentPanningVC respondsToSelector:selector]) { 
     [(id)self.currentPanningVC sidePanelWillStartMoving:self.currentPanningVC]; 
    } 

    if ([centerVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
     [centerVC respondsToSelector:selector]) { 
     [(id)centerVC sidePanelWillStartMoving:self.currentPanningVC]; 
    } 
} 

完了ブロック内のコードおよび非アニメーションコードブロックが同じです。そして、これはよくこのようなものです。私は両方の結果が同じであることを意味しますが、1つはアニメーション化されました。

これは本当にまったく同じ2つのコードブロックを持つことを迷惑に思いますが、どうすればそれを避けることができますか?

ありがとうございます!

答えて

4

ブロックオブジェクトを作成し、両方の場所で使用します。あなたのコードで

void (^yourBlock)(BOOL finished); 

yourBlock = ^{ 

     // same code as below 
     SEL selector = @selector(sidePanelWillStartMoving:); 
     if ([currentPanningVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
      [currentPanningVC respondsToSelector:selector]) { 
      [(id)self.currentPanningVC sidePanelWillStartMoving:self.currentPanningVC]; 
     } 

     if ([centerVC conformsToProtocol:@protocol(CHSurroundedViewDelegate)] && 
      [centerVC respondsToSelector:selector]) { 
      [(id)centerVC sidePanelWillStartMoving:self.currentPanningVC]; 
     } 
    } 

if (animated) { 
    [UIView animateWithDuration:0.3 animations:^{    
     view.frame = newFrame; 
    } completion:yourBlock]; 
} 
else { 
yourBlock(); 
} 
+0

ええと、これは完璧です!ありがとう、たくさんの人! – florion

+0

@flop嬉しいです! – Vignesh

7

は、アニメーションや完了コードのブロック変数を作成し、非アニメーションの場合には自分で呼び出します。たとえば、

void (^animatableCode)(void) = ^{ 
    view.frame = newFrame; 
}; 

void (^completionBlock)(BOOL finished) = ^{ 
    // ... 
}; 

if (animated) { 
    [UIView animateWithDuration:0.3f animations:animatableCode completion:completionBlock]; 

} else { 
    animatableCode(); 
    completionBlock(YES); 
} 
関連する問題