我有我的 LottieView
struct LottieView: UIViewRepresentable {
var name: String
var loopMode: LottieLoopMode = .loop
var contentMode: UIView.ContentMode = .scaleAspectFit
var paused: Bool = false
var shouldPlay: Bool = true
var animationView = AnimationView()
func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
let view = UIView(frame: .zero)
animationView.animation = Animation.named(name)
animationView.contentMode = contentMode
animationView.loopMode = loopMode
animationView.backgroundBehavior = .pauseAndRestore
if shouldPlay {
animationView.play()
}
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
])
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
if shouldPlay {
context.coordinator.parent.animationView.play { finished in
if context.coordinator.parent.animationView.loopMode == .playOnce && finished {
context.coordinator.parent.animationView.play()
DispatchQueue.main.asyncAfter(deadline: .now() 0.3) {
context.coordinator.parent.animationView.pause()
}
}
}
} else {
context.coordinator.parent.animationView.pause()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: LottieView
init(_ parent: LottieView) {
self.parent = parent
}
}
}
哪個影片的開始取決于它shouldPlay在視圖初始化程式中傳遞的屬性。
我在自定義 AddToCartButton 結構中使用 LottieView:
struct AddToCartButton: View {
let onAdd: () -> Void
@State private var shouldPresentAddAnimation: Bool = false
var body: some View {
Button {
withAnimation {
shouldPresentAddAnimation = true
onAdd()
}
} label: {
HStack(spacing: 0) {
LottieView(name: "add_to_cart_2",
loopMode: .playOnce,
contentMode: .scaleAspectFit,
shouldPlay: shouldPresentAddAnimation)
.frame(minWidth: 50, maxHeight: 40)
Text("Add to Cart")
.font(.ssButton)
.foregroundColor(.ssWhite)
.padding(.all, 10)
}
.padding(.vertical, 5)
.background {
RoundedRectangle(cornerRadius: 5)
}
.fixedSize(horizontal: true, vertical: false)
}
}
}
由于 LottieViewupdateUIView方法中的代碼,單擊此按鈕應該播放一次影片,然后回傳初始影片狀態。
我有我的主要視圖,其中有許多這樣創建的 AddToCartButton 結構:
AddToCartButton {
[some code...]
}
效果是在第一次單擊按鈕時,它會正確影片。在第二個不同的按鈕上單擊第二個,第一個影片會觸發。單擊第三個按鈕時,所有三個按鈕都會觸發影片。附照片中的樣本:
一、按鍵的初始狀態:

其次,一鍵點擊后:

最后,在第二個按鈕單擊后(其中兩個觸發影片):

我想要的是只有被點擊的按鈕才會觸發它的影片。
uj5u.com熱心網友回復:
我認為問題在于您沒有在播放影片后shouldPresentAddAnimation回傳。false因此,每次您按下按鈕時,都會呈現整個串列,并且由于您的 state 屬性是true,它會觸發影片。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/521930.html
標籤:IOS迅速迅捷乐蒂
