![](/img/trans.png)
[英]SwiftUI: How to run action when user releases screen from a longPressGesture?
[英]Trigger action when releasing LongPressGesture SwiftUI
當我在 minimumDistance 內釋放 LongPressGesture 時,我試圖觸發“按下”消息,但是當我長按圖像時,此代碼會立即打印出消息。 我該如何解決這個問題?
struct ContentView: View {
@GestureState private var isDetectingPress = false
var body: some View {
Image(systemName: "trash")
.resizable().aspectRatio(contentMode: .fit)
.frame(width: 100, height: 100)
.scaleEffect(isDetectingPress ? 0.5 : 1)
.animation(.easeInOut(duration: 0.2))
.gesture(LongPressGesture(minimumDuration: 0.01).sequenced(before:DragGesture(minimumDistance: 100).onEnded {_ in
print("Ended")
})
.updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
// The message below should be printed when I release the long press
print("pressed")
case .second(true, _):
state = false
break
default:
break
}
})
}
}
您可以嘗試以下方法:
struct ContentView: View {
var body: some View {
Button(action: {
print("Pressed")
}) {
Image(systemName: "trash")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100, height: 100)
}
.buttonStyle(ScalableButtonStyle())
}
}
struct ScalableButtonStyle: ButtonStyle {
let scaleWhenPressed: CGFloat = 0.75
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? scaleWhenPressed : 1.0)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.