简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM