I am trying to implement a Lottie AnimationView
inside my app but I am having trouble resizing the view.
This is how I setup/constrain
the AnimationView
:
@objc func showAnimationTapped(){
let logoAnimation = AnimationView(name: "StrokeAnimation")
logoAnimation.contentMode = .scaleAspectFit
self.view.addSubview(logoAnimation)
logoAnimation.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
logoAnimation.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
logoAnimation.heightAnchor.constraint(equalToConstant: 200).isActive = true
logoAnimation.widthAnchor.constraint(equalToConstant: 200).isActive = true
logoAnimation.play()
}
The problem is that XCode is breaking all the constraints and the AnimationView
is wrongly placed/scaled. I also checked the View Hirarchy
and the AnimationView
is actually covering the whole screen... Also tried it with CGRect
but that doesn't change anything.
How can I resize/constrain the animation in Swift 5?
I couldn't find anything on this topic.. I am grateful for every help!
Maybe something is wrong with my AE-file, because when I previewed it on Lottiefiles.com the "Stroke" is not the same animation as in me AE-file.
However I also tested it with a file directly from Lottie and that caused the same problem...
So maybe there is a Swift/Lottie/AfterEffects expert who can help me out here :)
Here is my AE-File + JSON-file for a better understanding. If there is anything unclear, just let me know.
Since you are giving its own constraint manually, you forgot to disable (set it to false) translatesAutoresizingMaskIntoConstraints
, try with this:
@objc func showAnimationTapped(){
let logoAnimation = AnimationView(name: "StrokeAnimation")
logoAnimation.contentMode = .scaleAspectFit
logoAnimation.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(logoAnimation)
logoAnimation.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
logoAnimation.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
logoAnimation.heightAnchor.constraint(equalToConstant: 200).isActive = true
logoAnimation.widthAnchor.constraint(equalToConstant: 200).isActive = true
logoAnimation.play()
}
Remember, if translatesAutoresizingMaskIntoConstraints
is set to true (which is by default), the system automatically creates a set of constraints based on the view’s frame and its autoresizing mask, but you don't want that, you clearly want to set your own constraints as you did in code.
Side note: be aware of the fact that showAnimationTapped()
might be called many times, and you don't want to keep adding a logoAnimation
view each time, otherwise it will make your UI performance worst. Maybe you can put it in a computed var, add it and show/hide it or just put it in a computed var and add/remove it.