如何避免动画(completionBlock)和非动画代码之间存在重复的代码

flo*_*ion 0 cocoa animation objective-c duplicates ios

我有一个问题,我曾多次问过自己.我们来看下面的例子:

 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

完成块中的代码和非动画代码块是相同的.这通常是这样的,我的意思是两者的结果是相同的,除了一个是动画的.

这真的困扰我有两个完全相同的代码块,我怎么能避免这个?

谢谢!

Mik*_*ler 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);
}
Run Code Online (Sandbox Code Playgroud)