gpt4 book ai didi

ios - Swift 5 CAKeyframeAnimation - 应用程序移至后台后恢复图层动画

转载 作者:行者123 更新时间:2023-12-01 21:46:07 25 4
gpt4 key购买 nike

我有 View 显示小指示条(用于声音)

indicator bars

这是代码:

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..etc 使用它。

问题

当应用程序移至后台时,音乐播放器暂停,并在 IndicatorView state = .pause已分配,但是当应用程序返回时,用户点击播放,例如。在 IndicatorView state = .play playAnimation()被称为,条形层的速度为一……但根本没有动画。

Here is a short video to describe my problem

谢谢

最佳答案

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

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

希望能帮助到你 :)

关于ios - Swift 5 CAKeyframeAnimation - 应用程序移至后台后恢复图层动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62212871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com