当我点击不同的选项卡时,Lottie动画停止播放

9
我在我的应用中使用Lottie动画,并尝试在退出应用后保持动画在后台运行(不是强制关闭)...
我已经成功地做到了,但问题在于当我选择不同的选项卡并返回具有动画视图的选项卡时,动画会停止。

Screenshot

这是我的代码。

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()}}
    }
}
2个回答

38

Swift 5

有一个属性可以设置,它将恢复您的Lottie动画:

yourAnimationView.backgroundBehavior = .pauseAndRestore

默认情况下,该属性设置为.pause


这似乎解决了问题。谢谢。 - Vinayak
当您使用Lottie时,特别是用于TabBar时,它应该是单一颜色还是支持多种颜色?@Krekin对此有什么想法。我目前收到了一个带有多种颜色的Lottie,但选项卡栏不支持它。 - Gangadhar

8
更好的方法是使用viewWillAppear/viewDidAppear重新开始动画,并删除观察willEnterForegroundNotification
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if self.animation?.isAnimationPlaying == false {
       self.animation?.play()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接