释放 LongPressGesture SwiftUI 时触发动作
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)
}
}
当我在 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)
}
}