Todd Davies
Todd Davies

Reputation: 5522

iOS find if a view is animating

I'm trying to animate (fade in/out) a UILabel and I'm using the following code:

float newAlpha = 0.0;

//TODO:Check if the previous animation has finished

if(answer.alpha==0.0) {
    newAlpha = 1.0;
} else if(answer.alpha==1.0) {
    newAlpha = 0.0;
}
[UIView animateWithDuration:1.0 animations:^{
    answer.alpha = newAlpha;
}];

Where the TODO comment is, I want to check if the previous animation has finished and if it hasn't, exit the method. Is there some way of doing this?

Upvotes: 3

Views: 3965

Answers (3)

lawicko
lawicko

Reputation: 7344

Use animateWithDuration:animations:completion: method to do your "previous animation", and set a flag in the completion handler to indicate if it's finished or not. Then, check the same flag exactly where you have the TODO comment.

Edit: Example below

-(void) animation1 {
    // assume that alpha was 0 and we want the view to appear
    [UIView animateWithDuration:1.0 animations:^{
        answer.alpha = 1.0;
    } completion:^(BOOL finished){
        fristAnimationFinished = finished;
    }];
}

-(void) animation2 {
    float newAlpha = 0.0;

    if (!firstAnimationFinished)
        return;

    if(answer.alpha==0.0) {
        newAlpha = 1.0;
    } else if(answer.alpha==1.0) {
        newAlpha = 0.0;
    }
    [UIView animateWithDuration:1.0 animations:^{
        answer.alpha = newAlpha;
    }];
}

Upvotes: 1

holex
holex

Reputation: 24041

UPDATE #1:

you need a variable in your class:

BOOL _animationFinished;

and then you can use the following way for the animation:

float newAlpha = 0.0;

//TODO:Check if the previous animation has finished
if (_animationFinished == false) return;

if(answer.alpha==0.0) {
    newAlpha = 1.0;
} else if(answer.alpha==1.0) {
    newAlpha = 0.0;
}

[UIView animateWithDuration:1.0f animations:^{ answer.alpha = newAlpha; _animationFinished = false; } completion:^(BOOL finished){ _animationFinished = true; }];

it must be work.


ORIGINAL

I'm always checking the subject of the animation in this case, like this:

float newAlpha = 0.0;

//TODO:Check if the previous animation has finished
if (answer.alpha > 0.f || answer.alpha < 1.f) return; // it is always good enough for me
// ...or with AND it will cause the same effect:
// if (answer.alpha > 0.f && answer.alpha < 1.f) return;

if(answer.alpha==0.0) {
    newAlpha = 1.0;
} else if(answer.alpha==1.0) {
    newAlpha = 0.0;
}
[UIView animateWithDuration:1.0 animations:^{
    answer.alpha = newAlpha;
}];

Upvotes: 3

Mihir Mehta
Mihir Mehta

Reputation: 13833

If you're using UIView then

[UIView setAnimationDidStopSelector:@selector(animationfinished)];
-(void) animationfinished
{
      animationFinished = YES;
}

Upvotes: 2

Related Questions