当我点击不同的标签栏项目时,Lottie 动画停止了
Lottie animation stopped when i tap on different tab bar item
我在我的应用程序中使用 Lottie 动画,当我退出应用程序并再次打开它(不是强制关闭)时,我试图将动画 运行 保留在后台......
我能够成功地做到这一点,但问题是当我 select 不同的标签栏项目并返回到具有动画视图的标签栏项目时动画停止。
这是我的代码。
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()}}
}
}
更好,使用 viewWillAppear/viewDidAppear
再次启动动画并移除观察 willEnterForegroundNotification
。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.animation?.isAnimationPlaying == false {
self.animation?.play()
}
}
Swift 5
有一个 属性,可以设置,它会恢复你的 Lottie 动画:
yourAnimationView.backgroundBehavior = .pauseAndRestore
默认情况下,此 属性 设置为 .pause
我在我的应用程序中使用 Lottie 动画,当我退出应用程序并再次打开它(不是强制关闭)时,我试图将动画 运行 保留在后台......
我能够成功地做到这一点,但问题是当我 select 不同的标签栏项目并返回到具有动画视图的标签栏项目时动画停止。
这是我的代码。
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()}}
}
}
更好,使用 viewWillAppear/viewDidAppear
再次启动动画并移除观察 willEnterForegroundNotification
。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.animation?.isAnimationPlaying == false {
self.animation?.play()
}
}
Swift 5
有一个 属性,可以设置,它会恢复你的 Lottie 动画:
yourAnimationView.backgroundBehavior = .pauseAndRestore
默认情况下,此 属性 设置为 .pause