swiftswiftuiuigesturerecognizeruilongpressgesturerecogni

How to fail a LongPressGesture on SwiftUI


I'm trying to fail LongPressGesture with maximumDistance when I move my finger away from the Image but that doesn't work, it keeps printing the message "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
                }
        })
    }
}

Solution

  • Change your updating modifier to detect if there is a drag amount:

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

    And set a minimum distance (eg. 100) for DragGesture in DragGesture itself:

    DragGesture(minimumDistance: 100)
    

    and not in LongPressGesture:

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