我刚刚用一个简单的动画构建了一个iOS应用程序。但我正在与UIViewPropertyAnimator作斗争。我想要动画一个按钮,这工作得很好,直到我离开应用程序(按下主页按钮)并返回它。动画已停止,不会再次启动。我试图停止动画,并在ViewController didBecomeActive之后再次启动它,但也不起作用。
我在viewDidAppear方法中启动动画,如下所示:
var animator: UIViewPropertyAnimator!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification,object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeInActive), name: UIApplication.willResignActiveNotification,object: nil)
//Start Animation
animator = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1, delay: 0, options: [.autoreverse, .repeat], animations: {
UIView.setAnimationRepeatAutoreverses(true)
UIView.setAnimationRepeatCount(1000)
self.scanButton.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}, completion: nil)
animator.startAnimation()
}下面是我停止和重新启动动画的代码:
@objc func applicationDidBecomeActive() {
print("Active")
animator.startAnimation()
}
@objc func applicationDidBecomeInActive() {
print("InActive")
animator.stopAnimation(true)
animator.finishAnimation(at: .current)
}我希望你们知道怎么解决这个问题。提前谢谢。
发布于 2020-01-30 09:42:49
您可以使用animator的任何一个初始化器将其设置为实例属性:
private var animator = UIViewPropertyAnimator(duration: 1, curve: .linear, animations: nil)这将允许您使用addAnimations()向其重新添加动画,这正是我们想要做的,因为动画本身在每次调用结束时都会被嵌套起来以启动一个调用。因此,在调用startAnimation()之前,我们必须始终为它提供动画(通常每次都是相同的)。
@objc func applicationDidBecomeActive() {
print("Active")
animator.addAnimations {
// re-add animation
}
animator.startAnimation()
}您也可以将动画添加到初始化器本身,但因为我们在每次调用start之前添加它,所以我认为这样更清晰。
https://stackoverflow.com/questions/59976491
复制相似问题