首页 > 解决方案 > 通用类 Lottie swift

问题描述

我是 Swift 的新手,我来自 objc .. 事实上,我需要在 Swift“通用”中做一个类,以便由我在 objc 中完成的项目的控制器调用。具体来说,我必须为项目的动画“替换”“Lottie”库中的几行代码。我只需要在 obj c 中编写我的 Swift 类方法。你能帮帮我吗?我创建了这个 Swift 类,但我在 superView 上崩溃了,但我不确定这只是问题所在......

这是我需要在 Swift 中替换的代码:

LOTAnimationView *lottie1Aux = [LOTAnimationView animationNamed:[dict valueForKey:SLIDER_MAP_IMG_KEY]];
lottie1Aux.contentMode = UIViewContentModeScaleToFill;
lottie1Aux.frame = slide.tutorialImageView.bounds;
lottie1Aux.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
lottie1Aux.loopAnimation = YES;
[slide.tutorialImageView addSubview:mySwiftClass];

这是我可以用来替换和优化的 Swift 类......

import Foundation
import Lottie
import UIKit

@objc
public class myClass: UIViewController {

    var alertView: AnimationView!

    override public func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        createView()
    }

    @objc public func createView() {
        // Create a red view
        let alertWidth: CGFloat = view.bounds.width
        let alertHeight: CGFloat = view.bounds.height
        let alertViewFrame: CGRect = CGRect(x: 0, y: 0, width: alertWidth, height: alertHeight)
        alertView = UIView(frame: alertViewFrame) as! AnimationView
        alertView.backgroundColor = UIColor.red

        // Create an image view and add it to this view
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: alertWidth, height: alertHeight/2))
        imageView.image = UIImage(named: "tour_merchant_pagamento")
        alertView.addSubview(imageView)
       //view.addSubview(alertView)

       alertView = AnimationView(name: "tour_merchant_pagamento")
       alertView.contentMode = UIViewContentMode.scaleToFill
       alertView.loopMode = .loop

}

标签: objective-cswiftclasslottie

解决方案


我发现您只是想将上面给出的 Objective-C 代码转换为最新的 Swift。我想说它比以前容易多了,你可以在 iOS 部分的 Lottie 网站上找到指南。

现在让我们将您的代码转换为 Swift。

首先下载并将所有 Lottie json 文件拖放到 Xcode 项目中的单独文件夹中,并根据需要简单命名。

1-您现在可以通过为您希望将动画分配到所需的 ViewController 类中的单独 UIView 创建一个出口来简化它。在创建插座之前,不要忘记去类检查器并在自定义类中选择 AnimationView。

然后导入 Lottie 并查看下面给出的代码示例。

import UIKit
import Lottie

class yourClass: UIViewController {
@IBOutlet var yourAnimationView: AnimationView!   //the outlet of animationView
    
 override func viewDidLoad() {
     
   createAnimationView()
  
 }

 func createAnimationView() {

  let yourAnimation = AnimationView(name: "filename") //animation object

  yourAnimationView.addSubview(yourAnimation)
  yourAnimationView.play() 


}

这比你想象的要简单。


推荐阅读