import SwiftUI import Lottie struct LottieView: UIViewRepresentable { let name: String let loopMode: LottieLoopMode let animationSpeed: CGFloat init(name: String, loopMode: LottieLoopMode = .loop, animationSpeed: CGFloat = 1.0) { self.name = name self.loopMode = loopMode self.animationSpeed = animationSpeed } func makeUIView(context: Context) -> LottieAnimationView { let animationView = LottieAnimationView() // 方法1: 直接使用文件名加载 if let animation = LottieAnimation.named(name) { animationView.animation = animation } // 方法2: 如果方法1失败,尝试使用文件路径加载 else if let path = Bundle.main.path(forResource: name, ofType: "json") { let animation = LottieAnimation.filepath(path) animationView.animation = animation } // 配置动画 animationView.loopMode = loopMode animationView.animationSpeed = animationSpeed animationView.contentMode = .scaleAspectFit animationView.backgroundBehavior = .pauseAndRestore // 播放动画 animationView.play() return animationView } func updateUIView(_ uiView: LottieAnimationView, context: Context) { // 确保动画持续播放 if !uiView.isAnimationPlaying { uiView.play() } } }