https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
s

Sumit Jha

11/28/2023, 11:28 AM
Is there any support for using Lottie Animation in KMM?
a

Anonymike

11/28/2023, 5:14 PM
There is nothing really necessary for KMM to support lottie. We use lottie in swiftui and compose for android in our KMM projects. What kind of support were you looking for?
s

Sumit Jha

11/28/2023, 5:41 PM
Thanks for your thoughts @Anonymike. Actually with native we used to add a Lottie dependency and then we're able use 'LottieAnimationView' to use, I was looking how could we do same with KMM
a

Anonymike

11/28/2023, 8:04 PM
We use the later lottie swift packages and made a View like the following. Originally we used dotLottie and had this view support both since the Lottie library didn't support it directly, so most of this is a pass-through now.
Copy code
import Lottie
import SwiftUI

public struct LottieView: UIViewRepresentable {
	let name: String
	var contentMode: UIView.ContentMode
	var loopMode: LottieLoopMode
	var speed: CGFloat

    public var completionHandler: LottieCompletionBlock?

	let animationView = LottieAnimationView()

	public init(name: String, contentMode: UIView.ContentMode = .scaleAspectFit, loopMode: LottieLoopMode = .loop, speed: CGFloat = 1.0, completionHandler: LottieCompletionBlock? = nil) {
		self.name = name
		self.contentMode = contentMode
		self.loopMode = loopMode
		self.speed = speed
		self.completionHandler = completionHandler
	}

    public func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
		let view = UIView(frame: .zero)

        if let animation = LottieAnimation.named(name) {
            animationView.animation = animation
            animationView.contentMode = contentMode
            animationView.loopMode = loopMode
            animationView.animationSpeed = speed

            animationView.translatesAutoresizingMaskIntoConstraints = false

            view.addSubview(animationView)
            animationView.play(completion: completionHandler)

            NSLayoutConstraint.activate([
                animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
                animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
            ])
        } else {
            print("Error loading .lottie")
        }

		return view
	}

    public func updateUIView(_ uiView: UIViewType, context: Context) {}
}
I edited trying to get syntax highlighting for swift working, but clearly slack and I have a misunderstanding 😂
2 Views