Ios Swift 5 CAKeyframeAnimation-在应用程序移动到地面后恢复层动画

Ios Swift 5 CAKeyframeAnimation-在应用程序移动到地面后恢复层动画,ios,swift,cakeyframeanimation,Ios,Swift,Cakeyframeanimation,我可以查看显示小指示条(用于声音) 下面是代码: class IndicatorView: UIViewController { enum AudioState { case stop case play case pause } var state: AudioState! { didSet { switch state { case .pause: pauseAnimation()

我可以查看显示小指示条(用于声音)

下面是代码:

class IndicatorView: UIViewController {

enum AudioState {
    case stop
    case play
    case pause
}

var state: AudioState! {
    didSet {
        switch state {
        case .pause:
            pauseAnimation()
        case .play:
            playAnimation()
        default:
            stopAnimation()
        }
    }
}

var numberOfBars: Int = 5
var barWidth: CGFloat = 4
var barSpacer: CGFloat = 4
var barColor: UIColor = .systemPink

private var bars: [UIView] = [UIView]()


private func stopAnimation() {
    bars.forEach { $0.alpha = 0 }
}

private func pauseAnimation() {
    bars.forEach {
        $0.layer.speed = 0
        $0.transform = CGAffineTransform(scaleX: 1, y: 0.1)
    }

}

private func playAnimation() {
    bars.forEach {
        $0.alpha = 1
        $0.layer.speed = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .clear

    DispatchQueue.main.async {
        self.setupViews()
    }
}


private func setupViews() {
    for i in 0...numberOfBars - 1 {
        let b = UIView()
        b.backgroundColor = barColor
        addAnimation(to: b)
        view.addSubview(b)
        bars.append(b)
        b.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: nil,
                 padding: .init(top: 0, left: CGFloat(i) * (barWidth + barSpacer), bottom: 0, right: 0),
                 size: .init(width: barWidth, height: 0))
    }

    stopAnimation()
}

private func addAnimation(to v: UIView) {

    let animation = CAKeyframeAnimation()
    animation.keyPath = "transform.scale.y"
    animation.values = [0.1, 0.3, 0.2, 0.5, 0.8, 0.3, 0.99, 0.72, 0.3].shuffled()
    animation.duration = 1
    animation.autoreverses = true
    animation.repeatCount = .infinity
    v.layer.add(animation, forKey: "baran")
}
}

工作很好。我是从另一个vc那里用的,等等

问题 当应用程序移到后台时,音乐播放器暂停,并处于<代码>指示灯视图<代码>状态=。暂停<代码>已分配,但当应用程序返回时,用户点击播放,例如在<代码>指示灯视图<代码>状态=。播放<代码>
playamation()
被调用,条层的速度为1。。。但根本没有动画片


谢谢

当应用程序转到后台时,CALayer动画将暂停。您可以实现在转到bg/fg时暂停和恢复动画的方法,但对于您的情况,如果将对“addAnimation(to:b)”的调用从SetupView移动到“playAnimation()”方法,则可以保证动画始终存在。例:

bars.forEach {
        $0.alpha = 1
        addAnimation(to: $0)
        $0.layer.speed = 1
  }

希望有帮助:)

是的,您指向正确的方向adri,只需首先检查层是否有动画,然后调用
addAnimation
方法