I have successfully implemented Lottie into my program by giving it its own view. Although once called, the animation only plays once. How would I make it so the animation loops?
LottieView (View with Lottie):
import SwiftUI
import Lottie
struct LottieView: UIViewRepresentable {
typealias UIViewType = UIView
var filename: String
func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
let view = UIView(frame: .zero)
let animationView = AnimationView()
let animation = Animation.named(filename)
animationView.animation = animation
animationView.contentMode = .scaleAspectFit
animationView.play()
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.widthAnchor.constraint(equalTo: view.widthAnchor), animationView.heightAnchor.constraint(equalTo: view.heightAnchor)
])
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
}
}
Current Implementation in ContentView:
HStack {
if isScroll {
LottieView(filename: "swipeLeft").frame(width: 200, height: 200)
.padding(.top, 500)
.padding(.leading, 100)
}
Spacer()
Button(action: {
SCLAlertView().showInfo("How to use:", subTitle: "Scroll across the screen to view panels. Then press on a panel to view more information.")
}) {
Image(systemName: "info.circle")
.padding(.trailing, 5)
.padding(.top, 400)
}
}
You can see that the Lottie animation is being played on the emulator. The Lottie animation will play infinite times, so to make sure that it only plays once, we are going to use the useRef and useEffect hooks so that it only plays once for 3 secs (3000 ms) when the app loads for the first time.
Ultimately, when you load the page, the loading speed matters, which makes Lottie a reasonable choice. These files can be easily used on iOS and Android. On the other hand, the GIF files are only 4-5 seconds long for 5 MB, which is a lot in real life and practically impossible to load every time.
You can set loop behavior for play calls. Add this code inside makeUIView(context:)
animationView.loopMode = .loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With