2012-05-07 24 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]; 
    } 
} 

完成塊和非動畫代碼塊中的代碼是相同的。這通常是這樣的,我的意思是兩者的結果是相同的,除了一個是動畫。

這確實困擾我有兩塊完全相同的代碼塊,我該如何避免這種情況?

謝謝!

回答

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); 
}