How to use Lottie Animation using storyboard

Viewed 948

I'm using the latest version of Xcode.

I have a JSON file whose name is "rainynight". I want to display it into 'View' component using storyboard.

Below is the code I wrote on my ViewController.

import UIKit
import Lottie

class ViewController: UIViewController {

@IBOutlet weak var animationView: AnimationView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    animationView.contentMode = .scaleAspectFit
    animationView.loopMode = .loop
    animationView.play()
}

and then, I went to attribute inspector to set the Animation View's Animation name.

Screenshot of main.stroyboard Screenshot of main.stroyboard

Until now, everything works fine.

The "rainynight" JSON file is shown in the view perfectly fine.

But the problem is that my ultimate goal is displaying several Lottie animations randomly.

Actually, I will connect Lottie animation with weather API but for convenience's sake let's say I want to display JSON files randomly.

For example, I have an array that contains JSON files' name like this.

let jsonArray = ["rainynight", "storm", "foggy"]

I have these JSON files on my file list. Screenshot of file list

But how do I show randomly one of these elements on the view using storyboard?

I know it can be solved super easily by writing a code.

But by writing a code, as far as I know, I can only set the animation in the center or something else.

I want the animation to be set at the place I exactly want it to be.

The location of the animation view can't be described with just simple word 'center'.

That's why I want to use storyboard.

1 Answers

Put a UIView wherever you want in your storyboard, and change the class name to AnimationView. Drag an outlet to your view controller.

Then the rest is just as easy.

@IBOutlet weak var animationView: AnimationView!
    
override func viewDidLoad() {
    super.viewDidLoad()

    let subAnimationView = AnimationView(name: "myAnimationName")
    animationView.contentMode = .scaleAspectFit
    animationView.addSubview(subAnimationView)
    subAnimationView.frame = animationView.bounds
    subAnimationView.play()
}
Related