Question

I am using the below code from Apple to pause and resume an animation.

When the pause button is clicked, I first pause the animation then displaying a popup. When the play button in the popup is clicked, I first remove the popup first then resume animation. The problem I face is that sometimes it is failing to resume. The animation remains paused. This is happening when I quickly pause and resuming animation repeatedly without delays.

- (void)pauseAnimation:(CALayer *)layer
{
    if (m_pCustomImageBtnObj != nil)
    {
        CFTimeInterval pausedTime =
            [layer convertTime:CACurrentMediaTime() fromLayer:nil];

        layer.speed = 0.0;
        layer.timeOffset = pausedTime;
    }
}

- (void)resumeAnimation
{
    if (m_pCustomImageBtnObj != nil)
    {
        CFTimeInterval pausedTime = [m_pCustomImageBtnObj.layer timeOffset];
        m_pCustomImageBtnObj.layer.speed = 1.0;
        m_pCustomImageBtnObj.layer.timeOffset = 0.0;
        m_pCustomImageBtnObj.layer.beginTime = 0.0;

        CFTimeInterval timeSincePause =
            [m_pCustomImageBtnObj.layer convertTime:CACurrentMediaTime()
                                          fromLayer:nil] - pausedTime;

        m_pCustomImageBtnObj.layer.beginTime = timeSincePause;
    }
}
Was it helpful?

Solution

i think you have to check if the animation did already resume during the current eventloop, or a pause did happen after all. Add thise condition to your resumeAnimation:

- (void)resumeAnimation
{
    if (m_pCustomImageBtnObj != nil)
    {
        CFTimeInterval pausedTime = [m_pCustomImageBtnObj.layer timeOffset];
        if (pausedTime != 0) { // check if resume is called before.
            m_pCustomImageBtnObj.layer.speed = 1.0;
            m_pCustomImageBtnObj.layer.timeOffset = 0.0;
            m_pCustomImageBtnObj.layer.beginTime = 0.0;

            CFTimeInterval timeSincePause =
            [m_pCustomImageBtnObj.layer convertTime:CACurrentMediaTime()
                                          fromLayer:nil] - pausedTime;

            m_pCustomImageBtnObj.layer.beginTime = timeSincePause;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top