0

我有一个问题我已经问过自己很多次了。让我们看看下面的例子:

 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

2 回答 2

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);
}
于 2012-05-07T12:57:14.307 回答
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();
}
于 2012-05-07T12:54:49.673 回答