在UIView动画中立即调用完成块

时间:2014-10-29 15:33:48

标签: ios uiview objective-c-blocks uianimation

我正在尝试逐个更改子视图的颜色,但即使我已将动画持续时间设置为2秒,所有视图的颜色也会立即更改。

- (void)runAnimation
{
    NSMutableArray *views = [[NSMutableArray alloc]init];

    for (UIView *bubble in self.subviews)
    {
        if(bubble.tag == 2500)
            [views addObject:bubble];
    }

    __weak PKCustomSlider *weak_self = self;
    __block NSInteger currentView = 0;
    self.animationBlock = ^{

        [UIView animateWithDuration:2 animations:^{
             NSLog(@"Animation block called again");
            [views[currentView] setBackgroundColor:[UIColor colorWithRed:1 green:0 blue:0 alpha:1]];
        } completion:^(BOOL finished) {
            currentView += 1;
            if(!finished)
            {
                NSLog(@"Animation hasn't finished");
                return;
            }

            if (currentView == views.count){
                currentView = 0;
                NSLog(@"Animation block ended");
            }
            else
            {
                weak_self.animationBlock();
                NSLog(@"Animation block called again because views still available in the array");
            }
        }];

    self.animationBlock();
}

1 个答案:

答案 0 :(得分:2)

如果您尝试为一个又一个视图制作动画,则不应该依赖完成块。如果动画块中没有动画,则可以立即调用完成块。

您可以这样做:

- (void)runAnimation
{
    for (int i = 0; i < self.subviews.count; i++) {
        UIView *bubble = self.subviews[i];

        if (bubble.tag != 2500)
            continue;

        [UIView animateWithDuration:2 delay:2*i options:0 animations:^{
            [bubble setBackgroundColor:[UIColor colorWithRed:0 green:1 blue:0 alpha:1]];
        } completion:nil];
    }
}