我正在快速制作一个简单的应用程序来测试 Lottie 动画库。当我第一次使用该应用程序时,代码运行良好。但是如果我从后台重新启动它,动画就会停止。
如何让动画在后台运行,以便当我切换到另一个应用程序并再次返回时,我看到动画正在运行。
我刚开始学习swift,所以我提前道歉。
import UIKit
import Lottie
class ViewController: UIViewController {
@IBOutlet weak var animationView: AnimationView!
override func viewDidLoad() {
super.viewDidLoad()
SetupAnimation()
}
func SetupAnimation() {
let animationView = AnimationView(name: "kiss")
animationView.frame = self.animationView.frame
self.animationView.addSubview(animationView)
animationView.loopMode = .autoReverse
animationView.contentMode = .scaleAspectFit
animationView.play()
}
}
最佳答案
有一件简单的事情可以帮助您播放动画。
在添加了动画的 View Controller 中添加以下 willEnterForegroundNotification
通知。
另一件事,全局声明 Lottie 的 AnimationView 实例。看下面代码
class MyClassVC: UIViewController {
@IBOutlet weak var animationView : UIView!
var animation : AnimationView?
func setupAnimation() {
animation = AnimationView(name: "kiss")
animation?.frame = self.animationView.bounds
self.animationView.addSubview(animation!)
animation?.loopMode = .autoReverse
animation?.contentMode = .scaleAspectFit
animation?.play()
}
@objc func applicationEnterInForground() {
if animation != nil {
if !(self.animation?.isAnimationPlaying)! {
self.animation?.play()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupAnimation()
NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterInForground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
}
这将在应用程序从后台进入前台时播放动画。
关于ios - 在后台运行应用程序的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899272/