Katherine Jenkins Katherine Jenkins - 2 years ago 457
Swift Question

How To Pause & Resume Animation - KDCircularProgress Circular Bar

I have amended some code I pulled from https://github.com/kaandedeoglu/KDCircularProgress

I have a small UIView which represents the circle progress timer. I have referenced it and also instantiated it to


I have managed to implement methods to start and reset the timer progress circular bar.

But I am having trouble restarting the circular progress bar when I pause the animation.

My code preamble:

import UIKit

class SomeTableViewController: UITableViewController {

//Circular progress vars
var currentCount = 1.0
let maxCount = 60.0

//Reference selected UIView & instantiate
@IBOutlet weak var circularProgressView: KDCircularProgress!

Start animation - 60 second animation:

if currentCount != maxCount {
currentCount += 1
circularProgressView.animateToAngle(360, duration: 60, completion: nil)

To stop and reset the animation:

currentCount = 0
circularProgressView.animateFromAngle(circularProgressView.angle, toAngle: 0, duration: 0.5, completion: nil)

To pause the animation:


How would I set up a method to restart the animation after the paused state?

Many thanks in advance for any clarification. It's my first animation, I have tried to resolve the matter myself, but cannot seem to find any syntax applicable to my particular case.

Answer Source

Pausing and resuming an animation takes special code. You might not be able to do it without modifying the library you are using.

The trick is to set the speed on the animation on the parent layer that's hosting the animation to 0 and record the time offset of the animation.

Here are a couple of methods (written in Objective-C) from one of my projects that pause and resume an animation:

- (void) pauseLayer: (CALayer *) theLayer
  CFTimeInterval mediaTime = CACurrentMediaTime();
  CFTimeInterval pausedTime = [theLayer convertTime: mediaTime fromLayer: nil];
  theLayer.speed = 0.0;
  theLayer.timeOffset = pausedTime;


- (void) removePauseForLayer: (CALayer *) theLayer;
  theLayer.speed = 1.0;
  theLayer.timeOffset = 0.0;
  theLayer.beginTime = 0.0;


- (void) resumeLayer: (CALayer *) theLayer;
  CFTimeInterval pausedTime = [theLayer timeOffset];
  [self removePauseForLayer: theLayer];
  CFTimeInterval mediaTime = CACurrentMediaTime();
  CFTimeInterval timeSincePause = 
    [theLayer convertTime: mediaTime fromLayer: nil] - pausedTime;
  theLayer.beginTime = timeSincePause;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download