Как играть в анимацию Lottie в Objective-C

Я установил файлы pod для Lottie и загрузил файл hello.json с сайта lottiefiles.com.

 LOTAnimationView *Hello_loader;
 Hello_loader = [LOTAnimationView animationNamed:@"hello"];
 [self.view addSubview:Hello_loader];

Я пробовал и в viewDidLoad(), и в viewDidAppear(), но все равно не появляется

Я новичок в этом программировании ios, может ли кто-нибудь помочь мне решить эту проблему? Заранее спасибо...


person RK ios    schedule 30.06.2018    source источник


Ответы (3)


В Lottie 3 класс Animation является Codable и недоступен непосредственно в Objective-C. Поэтому я создал оболочку, которая позволит использовать аналогичный API в Objevtice-C (вдохновленный это):

import Foundation
import UIKit
import Lottie

@objc(AnimationView) class Z_OBJC_Wrapper_AnimationView: UIView {

    @objc var loop:Bool {
        get {
            return animationView.loopMode == .loop
        }
        set {
            animationView.loopMode = newValue ? .loop : .playOnce
        }
    }

    @objc var speed:CGFloat {
        get {
            return animationView.animationSpeed
        }
        set {
            animationView.animationSpeed = newValue
        }
    }

    @objc var progress:AnimationProgressTime {
        get {
            return animationView.currentProgress
        }
        set {
            animationView.currentProgress = newValue
        }
    }

    private let animationView: AnimationView

    @objc override init(frame: CGRect) {
        animationView = AnimationView()

        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        animationView = AnimationView()

        super.init(coder: aDecoder)
        commonInit()
    }

    // MARK: - Public Functions

    @objc func loadAnimation(name animationName:String) {
        if let path = Bundle.main.path(forResource: animationName, ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let animation:Animation = try JSONDecoder().decode(Animation.self, from: data)
                animationView.animation = animation
            } catch {
                assertionFailure("Could not read Lottie json file")
            }
        }
    }

    /**
     Plays the animation from its current state to the end.

     - Parameter completion: An optional completion closure to be called when the animation completes playing.
     */
    @objc func play(completion: LottieCompletionBlock? = nil) {
        animationView.play(completion: completion)
    }

    /**
     Pauses the animation in its current state.

     The completion closure will be called with `false`
     */
    public func pause() {
        animationView.pause()
    }

    /**
     Stops the animation and resets the view to its start frame.

     The completion closure will be called with `false`
     */
    @objc func stop() {
        animationView.stop()
    }

    // MARK: Play with progress

    /**
     Plays the animation from a progress (0-1) to a progress (0-1).

     - Parameter fromProgress: The start progress of the animation.
     - Parameter toProgress: The end progress of the animation.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromProgress from: AnimationProgressTime,
                    toProgress to: AnimationProgressTime,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromProgress: from, toProgress: to, loopMode: loopMode, completion: completion)
    }

    /**
     Plays the animation from a progress (0-1) to a progress (0-1). The view's `loopMode` property will be used.

     - Parameter fromProgress: The start progress of the animation.
     - Parameter toProgress: The end progress of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromProgress from: AnimationProgressTime,
                    toProgress to: AnimationProgressTime,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromProgress: from, toProgress: to, loopMode: nil, completion: completion)
    }

    /**
     Plays the animation from the current progress to a progress (0-1).

     - Parameter toProgress: The end progress of the animation.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toProgress to: AnimationProgressTime,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromProgress: nil, toProgress: to, loopMode: loopMode, completion: completion)
    }

    /**
     Plays the animation from the current progress to a progress (0-1). The view's `loopMode` property will be used

     - Parameter toProgress: The end progress of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toProgress to: AnimationProgressTime,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromProgress: nil, toProgress: to, loopMode: nil, completion: completion)
    }

    // MARK: Play with frame

    /**
     Plays the animation from a start frame to an end frame in the animation's framerate.

     - Parameter fromFrame: The start frame of the animation.
     - Parameter toFrame: The end frame of the animation.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromFrame from: AnimationFrameTime,
                    toFrame to: AnimationFrameTime,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromFrame: from, toFrame: to, loopMode: loopMode, completion: completion)
    }

    /**
     Plays the animation from a start frame to an end frame in the animation's framerate. The view's `loopMode` property will be used.

     - Parameter fromFrame: The start frame of the animation.
     - Parameter toFrame: The end frame of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromFrame from: AnimationFrameTime,
                    toFrame to: AnimationFrameTime,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromFrame: from, toFrame: to, loopMode: nil, completion: completion)

    }

    /**
     Plays the animation from the current frame to an end frame in the animation's framerate.

     - Parameter toFrame: The end frame of the animation.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toFrame to: AnimationFrameTime,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromFrame: nil, toFrame: to, loopMode: loopMode, completion: completion)

    }

    /**
     Plays the animation from the current frame to an end frame in the animation's framerate. The view's `loopMode` property will be used.

     - Parameter toFrame: The end frame of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toFrame to: AnimationFrameTime,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromFrame: nil, toFrame: to, loopMode: nil, completion: completion)
    }

    // MARK: Play with marker

    /**
     Plays the animation from a named marker to another marker.

     Markers are point in time that are encoded into the Animation data and assigned
     a name.

     NOTE: If markers are not found the play command will exit.

     - Parameter fromMarker: The start marker for the animation playback.
     - Parameter toMarker: The end marker for the animation playback.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromMarker from: String,
                    toMarker to: String,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromMarker: from, toMarker: to, loopMode: loopMode, completion: completion)
    }

    /**
     Plays the animation from a named marker to another marker. The view's `loopMode` property will be used.

     Markers are point in time that are encoded into the Animation data and assigned
     a name.

     NOTE: If markers are not found the play command will exit.

     - Parameter fromMarker: The start marker for the animation playback.
     - Parameter toMarker: The end marker for the animation playback.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(fromMarker from: String,
                    toMarker to: String,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromMarker: from, toMarker: to, loopMode: nil, completion: completion)
    }

    /**
     Plays the animation the current progress to a named marker.

     Markers are point in time that are encoded into the Animation data and assigned
     a name.

     NOTE: If markers are not found the play command will exit.

     - Parameter toMarker: The end marker for the animation playback.
     - Parameter loopMode: The loop behavior of the animation.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toMarker to: String,
                    loop loopBool: Bool,
                    completion: LottieCompletionBlock? = nil) {
        let loopMode:LottieLoopMode = loopBool ? .loop : .playOnce
        animationView.play(fromMarker: nil, toMarker: to, loopMode: loopMode, completion: completion)
    }

    /**
     Plays the animation from the current progress to named marker. The view's `loopMode` property will be used.

     Markers are point in time that are encoded into the Animation data and assigned
     a name.

     NOTE: If markers are not found the play command will exit.

     - Parameter toMarker: The end marker for the animation playback.
     - Parameter completion: An optional completion closure to be called when the animation stops.
     */
    @objc func play(toMarker to: String,
                    completion: LottieCompletionBlock? = nil) {
        animationView.play(fromMarker: nil, toMarker: to, loopMode: nil, completion: completion)
    }

    // MARK: - Private

    private func commonInit() {
        translatesAutoresizingMaskIntoConstraints = false
        setUpViews()
    }

    private func setUpViews() {
        animationView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(animationView)
        animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

Использование в Objective-C:

AnimationView *loader = [[AnimationView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
[loader loadAnimationWithName:@"loader"];
[loader playWithCompletion:nil];

[self addSubview:loader];
person Axel Guilmin    schedule 04.10.2019
comment
Почему загрузчик добавляется как подзаголовок после того, как он был добавлен? Мне это кажется каким-то странным. - person Johan Karlsson; 12.06.2020

Swift 5 (с последней версией лотереи)

    let animationView = AnimationView(name: "Bubbles") //Replace "Bubbles" with your animation file name.
    animationView.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
    animationView.center = self.view.center
    animationView.loopMode = .loop
    animationView.backgroundBehavior = .pauseAndRestore //to pause in background and restart when it reach foreground
    self.view.addSubview(animationView)
    animationView.play()

Проверьте вывод по этой ссылке

person Hardik Thakkar    schedule 06.07.2018

попробуй это

 LOTAnimationView *hello_loader = [LOTAnimationView animationNamed:@"hello"];
 [self.view addSubview:hello_loader];
 [hello_loader play];
person Jigar    schedule 30.06.2018
comment
Все еще не работает... просматривает пустую страницу @IOS - person RK ios; 30.06.2018
comment
попробуй это [сам. Hello_loader играть]; - person Jigar; 30.06.2018
comment
приведенный выше код выдает ошибку [Свойство 'hello_loader' не найдено в объекте типа 'ViewController *'] - person RK ios; 30.06.2018
comment
проверьте отредактированный ответ, потому что вы уже объявляете объект Hello_loader - person Jigar; 30.06.2018
comment
это работает ... но нет, как я хочу, это просто показывает строку, но я хотел показать, что ссылка выше не могли бы вы мне помочь - person RK ios; 30.06.2018
comment
Я хотел загрузить привет в приведенном выше описании... но он просто показывает строки... не могли бы вы помочь мне в этом @IOS - person RK ios; 30.06.2018
comment
@RKios хорошо, подожди, я создам демо - person Jigar; 30.06.2018
comment
Вы создали это - person RK ios; 03.07.2018
comment
@RKios в чем проблема? - person Jigar; 03.07.2018
comment
NSInvalidArgumentException», причина: «-[ShopCollectionObject sizeWithAttributes:]: нераспознанный селектор отправлен экземпляру 0x60000026f200» - person RK ios; 03.07.2018
comment
Получил эту ошибку и сбой приложения в контроллере представления коллекции - person RK ios; 03.07.2018
comment
stackoverflow.com/ вопросы/51153018/ - person RK ios; 03.07.2018
comment
пожалуйста, проверьте эту ссылку @IOS - person RK ios; 03.07.2018
comment
эй нужна помощь @IOS - person RK ios; 04.07.2018
comment
пожалуйста, проверьте эту ссылку. @IOS - person RK ios; 05.07.2018
comment
приведенный выше код не работает. Не могли бы вы поделиться фрагментом кода Objective-C? - person pigeon_39; 05.08.2019
comment
Хотя этот код может ответить на вопрос, предоставление дополнительного контекста относительно того, почему и/или как этот код отвечает на вопрос, повышает его ценность в долгосрочной перспективе. - person Donald Duck; 30.11.2020