Ios 返回应用程序时重新启动UIViewPropertyAnimator
我刚刚用一个简单的动画制作了一个iOS应用程序。但我正在努力使用UIViewPropertyImator。我想动画一个按钮,这很好地工作,直到我离开应用程序(按下主页按钮),并返回到它。动画已停止,不会再次启动。我试图停止动画,并在ViewController变为活动状态后再次启动它,但这也不起作用 我在ViewDidDisplay方法中启动动画,如下所示:Ios 返回应用程序时重新启动UIViewPropertyAnimator,ios,swift,uiviewanimation,uiviewpropertyanimator,Ios,Swift,Uiviewanimation,Uiviewpropertyanimator,我刚刚用一个简单的动画制作了一个iOS应用程序。但我正在努力使用UIViewPropertyImator。我想动画一个按钮,这很好地工作,直到我离开应用程序(按下主页按钮),并返回到它。动画已停止,不会再次启动。我试图停止动画,并在ViewController变为活动状态后再次启动它,但这也不起作用 我在ViewDidDisplay方法中启动动画,如下所示: var animator: UIViewPropertyAnimator! override func 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)
}
我希望你们知道如何解决这个问题。
提前感谢。您可以使用其任何一个初始值设定项将
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()
}