-1

I use this code to create rotation animation for my imageView:

func rotate(imageView: UIImageView, aCircleTime: Double) { 
        
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = -Double.pi * 2 
        rotationAnimation.duration = aCircleTime
        rotationAnimation.repeatCount = .infinity
        imageView.layer.add(rotationAnimation, forKey: nil)
    }

But how to pause this animation?

User
  • 121
  • 1
  • 2
  • 11
  • `imageView.layer.speed=0` ? – matt Sep 13 '20 at 19:53
  • @matt I have a rotation animation. And when I press the pause button my imageVIew should stop at the current rotation angle. And in your case, it just stops at the starting point. – User Sep 13 '20 at 20:10
  • @matt Isn't this community all about asking questions? To make it easier for others to search? – User Sep 13 '20 at 20:19
  • I'm not sure what you are asking me. This is an encyclopedia of question-answer topics. There are already question-answer topics on the thing you are having trouble with, so to get work done, look at those and you will see what to do. – matt Sep 13 '20 at 20:21
  • I just did a search and one answer even links to an Apple document on this very topic: https://developer.apple.com/library/archive/qa/qa1673/_index.html – matt Sep 13 '20 at 20:24

1 Answers1

1

It's possible to pause and resume CAAnimations, but it's fussy and a little confusing. Take a look at this project on Github:

https://github.com/DuncanMC/ClockWipeSwift.git

It uses an extension on CALayer:

//  Credit to Rand, from Stack Overflow, for the basis of this extension
//  see https://stackoverflow.com/a/59079995/205185

import UIKit
import CoreGraphics

import Foundation

extension CALayer
{

    func isPaused() -> Bool {
        return speed == 0
    }

    private func internalPause(_ pause: Bool) {
        if pause {
            let pausedTime = convertTime(CACurrentMediaTime(), from: nil)
            speed = 0.0
            timeOffset = pausedTime
        } else {
            let pausedTime = timeOffset
            speed = 1.0
            timeOffset = 0.0
            beginTime = 0.0
            let timeSincePause = convertTime(CACurrentMediaTime(), from: nil) - pausedTime
            beginTime = timeSincePause
        }
    }


    func pauseAnimation(_ pause: Bool) {
        if pause != isPaused()  {
            internalPause(pause)
        }
    }

    func pauseOrResumeAnimation() {
        internalPause(isPaused())
    }
}

Pausing and resuming is much easier if you use UIView animation and UIViewPropertyAnimator. There are lots of tutorials that explain how to do it.

You can look at this project on Github that shows how to use UIViewPropertyAnimator.

Duncan C
  • 128,072
  • 22
  • 173
  • 272