58 lines
1.8 KiB
Swift
58 lines
1.8 KiB
Swift
import SwiftUI
|
||
import Lottie
|
||
|
||
struct LottieView: UIViewRepresentable {
|
||
let name: String
|
||
let loopMode: LottieLoopMode
|
||
let animationSpeed: CGFloat
|
||
let isPlaying: Bool
|
||
|
||
init(name: String, loopMode: LottieLoopMode = .loop, animationSpeed: CGFloat = 1.0, isPlaying: Bool = true) {
|
||
self.name = name
|
||
self.loopMode = loopMode
|
||
self.animationSpeed = animationSpeed
|
||
self.isPlaying = isPlaying
|
||
}
|
||
|
||
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
|
||
|
||
// 播放/暂停
|
||
if isPlaying {
|
||
animationView.play()
|
||
} else {
|
||
animationView.pause()
|
||
}
|
||
|
||
return animationView
|
||
}
|
||
|
||
func updateUIView(_ uiView: LottieAnimationView, context: Context) {
|
||
// 根据 isPlaying 控制播放/暂停
|
||
if isPlaying {
|
||
if !uiView.isAnimationPlaying {
|
||
uiView.play()
|
||
}
|
||
} else {
|
||
if uiView.isAnimationPlaying {
|
||
uiView.pause()
|
||
}
|
||
}
|
||
}
|
||
} |