2012-05-07 68 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); 
}