简体   繁体   中英

Completion block called immediatly in UIView animation

I am trying to change the colors of the subviews one by one but colors of all views are change immediately even though I have set the animation duration is 2seconds.

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

If you're trying to animate one view after another, you shouldn't have to rely on the completion block. The completion block can be called instantly if there is no animation to be done in the animation block.

You can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM