Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Lottie animation loop

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)
                       
        }
        
    
        }
like image 535
Devin Hadley Avatar asked Jun 25 '20 21:06

Devin Hadley


People also ask

How do you play Lottie animation only once?

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.

Is Lottie better than GIF?

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.


1 Answers

You can set loop behavior for play calls. Add this code inside makeUIView(context:)

animationView.loopMode = .loop
like image 75
Dscyre Scotti Avatar answered Oct 20 '22 20:10

Dscyre Scotti