如何避免在动画 (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];
    }
}

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

这真的让我困扰着两个完全相同的代码块,请问我该如何避免呢?

谢谢!

为动画和完成代码创建块变量,并在非动画情况下自行调用它们。例如:

void (^animatableCode)(void) = ^{
    view.frame = newFrame;
};
void (^completionBlock)(BOOL finished) = ^{
    // ...
};
if (animated) {
    [UIView animateWithDuration:0.3f animations:animatableCode completion:completionBlock];
} else {
    animatableCode();
    completionBlock(YES);
}

创建块对象并在两个地方使用它!

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

最新更新