首页 > 解决方案 > 如何在 SwiftUI 上使 LongPressGesture 失败

问题描述

当我将手指从图像上移开时,我试图用 maximumDistance 使 LongPressGesture 失败,但这不起作用,它会一直打印消息“Pressed”

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
                }
        })
    }
}

标签: swiftswiftuiuigesturerecognizeruilongpressgesturerecogni

解决方案


更改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
    }

并为其自身设置一个最小距离(例如 100 DragGestureDragGesture

DragGesture(minimumDistance: 100)

而不是LongPressGesture

//LongPressGesture(minimumDuration: 0.01, maximumDistance: 100) // remove `maximumDistance`
LongPressGesture(minimumDuration: 0.01)

推荐阅读