Last active
October 24, 2022 15:52
-
-
Save simibac/2d1e7107b6ccb15ea00ce1905319899d to your computer and use it in GitHub Desktop.
SwiftUI with Lottie Animation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State var play = 0 | |
var body: some View { | |
VStack{ | |
LottieView(name: "checkmark", play: $play) | |
.frame(width:100, height:100) | |
Button("Play"){ self.play += 1 } | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Lottie | |
struct LottieView: UIViewRepresentable { | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
var name: String! | |
@Binding var play:Int | |
var animationView = AnimationView() | |
class Coordinator: NSObject { | |
var parent: LottieView | |
init(_ animationView: LottieView) { | |
self.parent = animationView | |
super.init() | |
} | |
} | |
func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView { | |
let view = UIView() | |
animationView.animation = Animation.named(name) | |
animationView.contentMode = .scaleAspectFit | |
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>) { | |
animationView.play() | |
} | |
} |
Author
simibac
commented
Feb 17, 2020
•
Thanks for the snippet, I would replace var name: String!
with let name: String
to avoid force unwrapping crash.
we need update
code is not working
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment