Discover What’s New in Lottie 4.3.0 in SwiftUI

AsyncLearn
3 min readOct 5, 2023

--

Version 4.3.0 of Lottie comes with official support for SwiftUI. We no longer need to create a UIViewRepresentable, but we can directly use its new view LottieView. To try out this new view, follow these steps:

  • Install Lottie with Swift Package Manager.
  • Download an animation.
  • Use the animation.

Install Lottie with Swift Package Manager

Download an animation

You can find animations here: https://lottiefiles.com/featured

Once you’ve downloaded the JSON, add it to your project.

Use the animation

import Lottie

struct ContentView: View {
var body: some View {
LottieView(animation: .named("animationFile"))
}
}

By using the LottieView directly and passing the animation name as a parameter, .named("animationFile), we can display the animation.

If you run the project on a simulator or device, you will notice that the animation doesn't start; it remains static. To start the animation, Lottie provides several ways, as follows:

// The animation is played once and then stops.
LottieView(animation: .named("animationFile"))
.play()

// The animation will loop; once it finishes, it repeats from the beginning.
LottieView(animation: .named("animationFile"))
.looping()

// Displays the animation paused at the specified point, in this case, halfway through the animation.
LottieView(animation: .named("animationFile"))
.currentProgress(0.5)

Let’s try starting our animation:

import Lottie

struct ContentView: View {
var body: some View {
LottieView(animation: .named("animationFile"))
.play()
}
}

New Lottie Views in SwiftUI

In addition to LottieView, in this new update, we can use LottieButton and LottieSwitch.

LottieButton

To use the new Lottie button, simply use the LottieButton view with our animation and execute the desired action in the completionHandler.

import Lottie
import SwiftUI

struct ContentView: View {
var body: some View {
LottieButton(animation: .named("button")) {
// Action
}
}
}

LottieSwitch

To use the new Lottie switch view, use the LottieSwitch view with our animation and use the isOn modifier. Additionally, depending on the animation we use, we need to configure when the animation starts when isOn is true using .onAnimation(fromProgress: 0.0, toProgress: 0.5) and configure when the animation ends when isOn is false using .offAnimation(fromProgress: 0.5, toProgress: 1.0).

import Lottie
import SwiftUI

struct ContentView: View {
@State var isOn = false

var body: some View {
LottieSwitch(animation: .named("switch"))
.isOn($isOn)
.onAnimation(fromProgress: 0.0, toProgress: 0.5)
.offAnimation(fromProgress: 0.5, toProgress: 1.0)
}
}

--

--

AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.