Swift加载Lottie

OC使用时,需要通过swift透出方法供OC使用

objectivec 复制代码
// 此处文件名可以从Build Settings下搜索Generated Header Name的值得出
#import <Test-Swift.h>

一、导入包

dart 复制代码
target 'iOS' do
  use_frameworks!
  
  # 此处
  pod 'lottie-ios'
end

二、功能实现

1. 创建组件

swift 复制代码
import Lottie

@objcMembers class LottieAnimView: UIView, UIScrollViewDelegate {
	static let sharedManager: LottieAnimView = LottieAnimView()
	private var lotView: AnimationView = AnimationView()
	
  func createLottieView(path: String) {
      let sp = path.components(separatedBy: ".")
      
      if let filePath = Bundle.main.path(forResource: sp.first!, ofType: "json") {
          let animation = Animation.filepath(filePath)
          lotView.animation = animation
      }
      
      // 修改fill方式
      lotView.contentMode = .scaleToFill
      
      // true:视图会使用旧版的 Autoresizing Mask 来进行布局。这意味着视图的位置和大小将根据其父视图的边界和自身的自动布局规则进行自动调整
      // false:视图将使用 Auto Layout 进行布局。这意味着你可以通过约束(constraints)来精确地定义视图的位置、大小和相对关系。
      // 如果不设置此处,则设置宽高无效。好像只有在动态修改frame时无效
      lotView.translatesAutoresizingMaskIntoConstraints = true
      
      lotView.loopMode = .loop
      
      lotView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
      
      // 添加点击事件
      let tapGesture = UITapGestureRecognizer(target: self, action: #selector(animationViewTapped))
      lotView.addGestureRecognizer(tapGesture)
      lotView.isUserInteractionEnabled = true
      
      // 此处根据需要添加到父级ViewController上
      UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(lotView)
    }
    
    @objc func animationViewTapped(sender: UITapGestureRecognizer) {
        // 可以根据sender.view获取AnimationView
        print("点击了AnimationView")
    }
}

2. 常用方法

swift 复制代码
// 1. 播放
lotView.play()

// 2. 暂停
lotView.pause()

// 3. 取消
lotView.stop()

三、注意

  1. 可以动态修改loopMode方式
  2. 我们的使用场景是在lua层先调用createLottieView,之后立马play,此时发现会动画卡在第一帧,怀疑是线程堵塞,在play之前让出CPU的时间片1个游戏帧即可
相关推荐
二流小码农1 小时前
鸿蒙开发:web页面如何适配深色模式
android·ios·harmonyos
yuec4 小时前
iOS 26 你的 property 崩了吗?
ios·客户端
jiangmiao20247 小时前
IOS开发 Runloop机制
ios·objective-c
從南走到北7 小时前
JAVA国际版任务悬赏发布接单系统源码支持IOS+Android+H5
android·java·ios·微信·微信小程序·小程序
咕噜签名分发冰淇淋7 小时前
苹果ios安卓apk应用APP文件怎么修改手机APP显示的名称
android·ios·智能手机
游戏开发爱好者88 小时前
iOS 开发推送功能全流程详解 从 APNs 配置到上架发布的完整实践(含跨平台上传方案)
android·macos·ios·小程序·uni-app·cocoa·iphone
Larva9 小时前
iOS - 关于如何在编译时写入文件并在代码内读取文件内容
ios
HarderCoder12 小时前
Swift 模式:解构与匹配的安全之道
swift
东坡肘子12 小时前
Swift 官方发布 Android SDK | 肘子的 Swift 周报 #0108
android·swiftui·swift
胎粉仔21 小时前
Objective-C 初阶 —— __bridge & __bridge_retained & __bridge_transfer
ios·objective-c