Lottie view wrapper in SwiftUI
This file contains 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
// | |
// LottieView.swift | |
// | |
// Created by Mathijs Bernson on 27/10/2021. | |
// | |
import SwiftUI | |
import Lottie | |
struct LottieView: UIViewRepresentable { | |
let animation: Lottie.Animation? | |
let loopMode: LottieLoopMode | |
let contentMode: UIView.ContentMode | |
init( | |
animation: Lottie.Animation?, | |
loopMode: LottieLoopMode, | |
contentMode: UIView.ContentMode | |
) { | |
self.animation = animation | |
self.loopMode = loopMode | |
self.contentMode = contentMode | |
} | |
func makeUIView(context: Context) -> UIView { | |
let animationView = AnimationView() | |
animationView.contentMode = contentMode | |
animationView.animation = animation | |
animationView.loopMode = loopMode | |
animationView.play() | |
let uiView = UIView(frame: .zero) | |
animationView.translatesAutoresizingMaskIntoConstraints = false | |
uiView.addSubview(animationView) | |
NSLayoutConstraint.activate([ | |
uiView.topAnchor.constraint(equalTo: animationView.topAnchor), | |
uiView.bottomAnchor.constraint(equalTo: animationView.bottomAnchor), | |
uiView.leadingAnchor.constraint(equalTo: animationView.leadingAnchor), | |
uiView.trailingAnchor.constraint(equalTo: animationView.trailingAnchor), | |
uiView.widthAnchor.constraint(equalTo: animationView.widthAnchor), | |
uiView.heightAnchor.constraint(equalTo: animationView.heightAnchor), | |
]) | |
return uiView | |
} | |
func updateUIView(_ animationView: UIView, context: Context) { | |
// | |
} | |
} | |
struct LottieView_Previews: PreviewProvider { | |
static var previews: some View { | |
LottieView( | |
animation: .named("MyAnimation"), | |
loopMode: .loop, | |
contentMode: .scaleAspectFill | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment