我正在我的应用程序中使用Lottie动画,并试图在退出应用程序并再次打开它时使动画在后台运行(不是强制关闭)。
我能够成功执行此操作,但是问题是当我选择其他选项卡栏项目并返回到具有动画视图的选项卡栏项目时,动画停止了。
这是我的代码。
import UIKit
import Lottie
import UserNotifications
import NotificationCenter
class HomeViewController: UIViewController {
@IBOutlet weak var animationView: UIView!
var animation : AnimationView?
override func viewDidLoad() {
super.viewDidLoad()
setupAnimation()
NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterInForground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
func setupAnimation() {
animation = AnimationView(name: "cong")
animation?.frame = self.animationView.bounds
self.animationView.addSubview(animation!)
animation?.loopMode = .loop
animation?.contentMode = .scaleAspectFit
animation?.play()
}
@objc func applicationEnterInForground() {
if animation != nil {
if !(self.animation?.isAnimationPlaying)! {self.animation?.play()}}
}
}
答案 0 :(得分:1)
更好的是,使用viewWillAppear/viewDidAppear
重新开始动画,并删除对willEnterForegroundNotification
的观察。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.animation?.isAnimationPlaying == false {
self.animation?.play()
}
}
答案 1 :(得分:0)
快捷键5
有一个可以设置的属性,它将恢复您的Lottie动画:
yourAnimationView.backgroundBehavior = .pauseAndRestore
默认情况下,此属性设置为.pause