ios - 返回App时重启UIViewPropertyAnimator
问题描述
我刚刚构建了一个带有简单动画的 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)
}
我希望你们知道如何解决这个问题。提前致谢。
解决方案
你可以做的是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()
}
您也可以将动画添加到初始化程序本身,但由于我们在每次调用开始之前添加它,我认为这更干净。
推荐阅读
- awk - 基于 awk 中特定列的单个输入的多个输出
- php - PHP MySQL中的简单测验系统 - 正确和选择的选项
- python - Xarray:处理通过索引一个元素返回的无量纲数组的干净方法
- asp.net-mvc - 加载资源失败:将 ASP.NET MVC 服务器从 IIS Express 更改为本地 IIS 时出现 404 错误
- elasticsearch - 如何在elasticsearch中查询上个月的数据
- windows - Windows 10 命令提示符重命名文件会覆盖文件名而不是前置
- mysql - 如何使用 Python 获取 MYSQL 中的表之间的关系?
- latex - 如何在 beamercolor.sty 文件中设置书目文本颜色
- android - TextWatcher 在 DialogFragment 中不起作用
- postgresql - 在 Postgresql 中为列创建行