首页 > 解决方案 > 如何暂停 imageView 动画?

问题描述

我使用此代码为我的 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)
    }

但是如何暂停这个动画呢?

标签: iosswift

解决方案


可以暂停和恢复 CAAnimations,但它很繁琐而且有点混乱。看看 Github 上的这个项目:

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

它在 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())
    }
}

如果使用 UIView 动画和 UIViewPropertyAnimator,暂停和恢复会容易得多。有很多教程解释了如何做到这一点。

你可以在 Github 上查看这个项目,它展示了如何使用UIViewPropertyAnimator.


推荐阅读