SwiftUi Lottie动画在视图更新时失败



我正在尝试播放Lottie动画时,一些状态更新在我的SwiftUI视图。在下面的代码中,播放按钮将根据需要播放动画,但是,一旦我引入一个state属性,导致视图刷新,动画就会停止播放。有人知道怎么解吗?

LottieView UIViewRepresentable

import SwiftUI
import Lottie
struct LottieView: UIViewRepresentable {
let animationName:String

@Binding var play: Bool
var animationView:LottieAnimationView

init(animationName:String,
play: Binding<Bool> = .constant(true)
) {
self.animationName = animationName
self.animationView = LottieAnimationView(name: animationName)
self._play = play
}
class Coordinator: NSObject {
@Binding var play: Bool
let parent: LottieView
init(parent: LottieView, play: Binding<Bool>) {
self.parent = parent
_play = play
}  
}

func makeCoordinator() -> Coordinator {
return Coordinator(parent: self, play: $play)
}

func makeUIView(context: Context) -> UIView {
let view = UIView(frame: .zero)
view.addSubview(animationView)
animationView.translatesAutoresizingMaskIntoConstraints = false
animationView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
animationView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
return view
}

func updateUIView(_ uiView: UIView, context: Context) {
if play {
animationView.play { _ in
play.toggle()
}
}
}
}

ContentView

struct ContentView: View {
@State private var play = false
@State private var value = 0
var body: some View {
ZStack {
VStack {
Button("play") {
value += 1
play.toggle()
}
// Uncomment and this breaks
//                Text("The Value is (value)")
Rectangle()
.frame(width: 400, height: 400)
.foregroundColor(.clear)
.overlay {
LottieView(animationName: "confetti",
play: $play)
}
}
}
}
}

提供了一个解决方案,但是@iharis在Twitter上是分配一个id给react,这将强制视图在改变时重新渲染,所以如果我给它分配一个id值,那么矩形和LotieView覆盖将重新渲染。

struct ContentView: View {
@State private var play = false
@State private var value = 0
var body: some View {
ZStack {
VStack {
Button("play") {
value += 1
play.toggle()
}
Text("The Value is (value)")
Rectangle()
.id(value)
.frame(width: 400, height: 400)
.foregroundColor(.clear)
.overlay {
LottieView(animationName: "confetti",
play: $play)
}
}
}
}
}

最新更新