Tung Vo Duc
Tung Vo Duc

Reputation: 503

ios - cabasicanimation need to reset

I have 3 CABasicAnimation of 3 color bars which is following each other. After the third is completed, 3 bars will stay at their final position. Until here, everything is good, here is the code:

- (void)animationDidStop:(CABasicAnimation *)theAnimation finished:(BOOL)flag {
    NSString* value = [theAnimation valueForKey:@"id"];
    if([value isEqualToString:@"position1"]){
        [self playVideoAtIndex:1];
    }
    else if([value isEqualToString:@"position2"]){
        [self playVideoAtIndex:2];
    }
    else if([value isEqualToString:@"position3"]){

    }
}

Before that, I created 3 animations like this:

-(void)createAnimationAtIndex:(NSInteger)index{
UILabel *label = (UILabel *)[barLabelArray objectAtIndex:index];
if(index==0){
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;
    //SOMETHING HERE
    [label.layer addAnimation:animation forKey:@"position1"];
}
else if(index==1){
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;
    //SOMETHING HERE
    [self.delegate startPlayVideoAtIndex:1];
    [label.layer addAnimation:animation forKey:@"position2"];
}
else if(index==2){
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;
    //SOMETHING HERE
    [label.layer addAnimation:animation forKey:@"position3"];
}

}

So if I wait until all animations stop, when I come back, they will start animation properly again. But sometimes I need stoping the animation in the middle of it. And then when I come back and start the animation again, all is messed up. Here is code for stoping animations:

-(void)reset{
    for(UILabel *label in barLabelArray){
        [label.layer removeAllAnimations];
    }
}

So do you know what I am doing wrong here and how to fix it? Thank you !!

Upvotes: 1

Views: 336

Answers (1)

Mike
Mike

Reputation: 481

There is a way pause and resume any animations. Here is several good strings which can help you if I understand correctly

- (void) pauseLayer
{
    CFTimeInterval pausedTime = [label.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    label.layer.speed = 0.0;
    label.layer.timeOffset = pausedTime;
}

- (void) resumeLayer
{
    CFTimeInterval pausedTime = [label.layer timeOffset];
    label.layer.speed = 1.0;
    label.layer.timeOffset = 0.0;
    label.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [label.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    label.layer.beginTime = timeSincePause;
}

Upvotes: 1

Related Questions