wake-ios/wake/SharedUI/Animation/LottieView.swift

84 lines
2.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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) -> UIView {
// 使 LottieAnimationView SwiftUI frame
let container = UIView()
container.clipsToBounds = true
let animationView = LottieAnimationView()
animationView.translatesAutoresizingMaskIntoConstraints = false
// 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
container.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.leadingAnchor.constraint(equalTo: container.leadingAnchor),
animationView.trailingAnchor.constraint(equalTo: container.trailingAnchor),
animationView.topAnchor.constraint(equalTo: container.topAnchor),
animationView.bottomAnchor.constraint(equalTo: container.bottomAnchor)
])
// Coordinator 便 updateUIView
context.coordinator.animationView = animationView
// /
if isPlaying {
animationView.play()
} else {
animationView.pause()
}
return container
}
func updateUIView(_ uiView: UIView, context: Context) {
guard let animationView = context.coordinator.animationView else { return }
// isPlaying /
if isPlaying {
if !animationView.isAnimationPlaying {
animationView.play()
}
} else {
if animationView.isAnimationPlaying {
animationView.pause()
}
}
}
// 使 Coordinator make/update animationView
class Coordinator {
var animationView: LottieAnimationView?
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}