最近,我在玩Lottie动画,但是我遇到了一个问题,就是如何将它们从视图中停止。
这是我的ContentView,在这里我正在播放动画。我有一个按钮可以实时显示布尔值:
struct ContentView: View {
@State var isShowing : Bool = true
var body: some View {
ZStack {
Color.green.opacity(0.3)
VStack {
VStack {
LottieDosi(isShowing: .constant(isShowing)){Text("")}
Button(action: {self.isShowing.toggle()}) {
Text("Button is \(String(isShowing))")
.padding(10)
.background(Color.white)
.cornerRadius(40)
}
}.padding(.horizontal, 30)
}
}.edgesIgnoringSafeArea(.all)
}
}
这是我的 LottieView:
struct LottieView: UIViewRepresentable {
@Binding var isAnimating: Bool
@State var name : String
var loopMode: LottieLoopMode = .loop
var animationView = AnimationView()
func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
let view = UIView()
animationView.animation = Animation.named(name)
animationView.contentMode = .scaleAspectFill
animationView.loopMode = .loop
animationView.play()
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: UIViewRepresentableContext<LottieView>) {
isAnimating ? animationView.play() : animationView.stop()
}
}
struct LottieDosi<Content>: View where Content: View {
@Binding var isShowing: Bool
var content: () -> Content
var body: some View {
VStack {
LottieView(isAnimating: .constant(isShowing), name: "13728-sticker-4")
.frame(width: 175, height: 175)
}
}
}
我有一个布尔类型绑定,每当我点击按钮时都必须将其更改为true或false。换句话说,当我按下按钮时,应该能够播放和停止它。但是不知何故,这个布尔值在结构之间没有共享,动画一直在播放。我对Swift UI还很陌生,因此我认为我做错了一些事情,所以我希望得到一些帮助。
在这里您可以看到我的动画。
context.coordinator.parent.animationView.play { (_) in context.coordinator.parent.isPaused = true }
,这样当动画播放完毕后,它会自动暂停。 :) - emmics