Blaj Bogdan
Blaj Bogdan

Reputation: 455

Problems loading animations in Lottie

I am trying to use Lottie in my Xcode project. I encountered some problems from the start. I've looked on youtube and here for solutions but it would not fix it. I can't manage to start the animation, not even making it visible...

I installed cocoa pods, added the Lottie library, downloaded a json file to play it. I've created an UIImageView which I set to AnimationView class

    @IBOutlet weak var animationView: AnimationView!

    let filename = "bb8"

 func startAnimation() {

        let animation = Animation.named(filename)
        animationView.animation = animation
        animationView.contentMode = .scaleAspectFit
        animationView.play()
    }

I also tried a different approach but it does not work

        let path = Bundle.main.path(forResource: "bb8",
                                    ofType: "json") ?? ""
        animationView.animation = Animation.filepath(path)
        animationView.contentMode = .scaleAspectFit
        animationView.play()

I expect for my AnimationView to show something other than what I see on storyboards.

Upvotes: 1

Views: 2932

Answers (1)

Blaj Bogdan
Blaj Bogdan

Reputation: 455

I managed to fix this, it seems you can't make it with storyboards anymore. I created an animationView programatically and had the 2nd snippet of code, and it worked.

    var animationView: AnimationView = {
        var av = AnimationView()

        return av
    }()

    func initUI() {
        self.view.backgroundColor = .white
        animationView.backgroundColor = .white

        view.addSubview(animationView)
        animationView.translatesAutoresizingMaskIntoConstraints = false

        animationView.widthAnchor.constraint(equalToConstant: 250).isActive = true
        animationView.heightAnchor.constraint(equalToConstant: 250).isActive = true
        animationView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        animationView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    }
func startAnimation() {
        let path = Bundle.main.path(forResource: "bb8",
                                    ofType: "json") ?? ""
        animationView.animation = Animation.filepath(path)
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        animationView.play()


    }

I managed to solve it and create programatically my first UI. This code can be used if other people have the same issue and are new to Swift and Lottie.

Upvotes: 2

Related Questions