swiftUI3.0 使用Lottie动画
//
// LottieView.swift
// testLottieDemo1
//
// Created by lujun on 2022/1/29.
//
import SwiftUI
import Lottie
//SwiftUI 不能直接 使用 Lottie ,需要 桥接
struct LottieView: UIViewRepresentable{
//传入一个名字
var name: String!
@Binding var play: Int
var animationView = AnimationView.init()
//实现 Coordinator 桥接转化
func makeCoordinator() -> Coordinator {
//调用 Coordinator 的构造方法,把自身传进去
Coordinator(self)
}
//MARK: - 写一个类 初始化成员变量
class Coordinator: NSObject{
var parentView : LottieView
init(_ animationView: LottieView){
parentView = animationView
//最后调用父类
super.init()
}
}
func makeUIView(context: Context) -> UIView {
let view = UIView.init()
animationView.animation = Animation.named(name)
animationView.contentMode = .scaleAspectFit
// animationView.loopMode = .loop//动画的循环模式
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
//添加约束
NSLayoutConstraint.activate([
animationView.widthAnchor.constraint(equalTo: view.widthAnchor),
animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
])
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
if play < 1000 {
animationView.play { _ in
}
}
}
}
使用
//
// LottieView.swift
// testLottieDemo1
//
// Created by lujun on 2022/1/29.
//
import SwiftUI
import Lottie
//SwiftUI 不能直接 使用 Lottie ,需要 桥接
struct LottieView: UIViewRepresentable{
//传入一个名字
var name: String!
@Binding var play: Int
var animationView = AnimationView.init()
//实现 Coordinator 桥接转化
func makeCoordinator() -> Coordinator {
//调用 Coordinator 的构造方法,把自身传进去
Coordinator(self)
}
//MARK: - 写一个类 初始化成员变量
class Coordinator: NSObject{
var parentView : LottieView
init(_ animationView: LottieView){
parentView = animationView
//最后调用父类
super.init()
}
}
func makeUIView(context: Context) -> UIView {
let view = UIView.init()
animationView.animation = Animation.named(name)
animationView.contentMode = .scaleAspectFit
// animationView.loopMode = .loop//动画的循环模式
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
//添加约束
NSLayoutConstraint.activate([
animationView.widthAnchor.constraint(equalTo: view.widthAnchor),
animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
])
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
if play < 1000 {
animationView.play { _ in
}
}
}
}

浙公网安备 33010602011771号