Search code examples
ioscocoa-touchuitableviewuiviewcore-animation

How can I determine if an animation is currently playing in UIView?


I'd like to determine if a UITableView and other views are currently performing some type of animation with core animation.

In investigating this, I discovered the following Stack Overflow question & answer: how to tell if uiview is in middle of animation?

I've verified that this technique of checking the animationKeys property works great for controls like UISlider, however when attempting to check for animationKeys during a UITableView animation, the NSArray count is always 0. I even went so far as to recursively check every view and layer in the view hierarchy for animationKeys, and all of them had a count of 0.

In looking into the addAnimation:forKey: selector of CALayer, I discovered that it's possible to add an animation with a nil key. This is probably the reason animationKeys has a count of 0. Due to this, I can't use the above linked technique.

The question: Is it even possible to reliably determine if an animation is currently playing? If so, what are some techniques for determining this?


Solution

  • I would use the delegate methodanimationDidStart:

    Delegate Methods

    animationDidStart: Called when the animation begins its active duration.

    • (void)animationDidStart:(CAAnimation *)theAnimation Parameters theAnimation The CAAnimation instance that started animating. Availability Available in iOS 2.0 and later. Declared In CAAnimation.h

    Alternatively, you could query thepresentationLayerand compare it to the model layer. For example:

    CGPoint presentationPosition = myLayer.presentationLayer.position;
    CGPoint modelPosition = myLayer.position;
    
    BOOL animationInProgress = NO;
    
    if (presentationPosition.x != modelPosition.x ||
        presentationPosition.y != modelPosition.y)
    {
        animationInProgress = YES;
    }