如何在 SwiftUI 上使 LongPressGesture 失败
How to fail a LongPressGesture on SwiftUI
当我将手指从图像上移开时,我尝试使用最大距离使 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, maximumDistance: 10).sequenced(before:DragGesture(minimumDistance: 0).onEnded {_ in
print("Pressed")
})
.updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
default:
break
}
})
}
}
更改您的 updating
修改器以检测是否存在拖动量:
.updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
case .second(true, _): // add this case to handle `non-nil` drag amount
state = false
default:
break
}
并在 DragGesture
本身中为 DragGesture
设置最小距离(例如 100):
DragGesture(minimumDistance: 100)
而不是 LongPressGesture
:
//LongPressGesture(minimumDuration: 0.01, maximumDistance: 100) // remove `maximumDistance`
LongPressGesture(minimumDuration: 0.01)
当我将手指从图像上移开时,我尝试使用最大距离使 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, maximumDistance: 10).sequenced(before:DragGesture(minimumDistance: 0).onEnded {_ in
print("Pressed")
})
.updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
default:
break
}
})
}
}
更改您的 updating
修改器以检测是否存在拖动量:
.updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
case .second(true, _): // add this case to handle `non-nil` drag amount
state = false
default:
break
}
并在 DragGesture
本身中为 DragGesture
设置最小距离(例如 100):
DragGesture(minimumDistance: 100)
而不是 LongPressGesture
:
//LongPressGesture(minimumDuration: 0.01, maximumDistance: 100) // remove `maximumDistance`
LongPressGesture(minimumDuration: 0.01)