2

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
                }
        })
    }
}
xmetal
  • 681
  • 6
  • 16

1 Answers1

2

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)
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • the code works well and the animations is updating when I move the finger but the problem is that it still complete the action of printing "Pressed" – xmetal Jul 31 '20 at 23:11
  • I cannot because I have to perform an action when I tap on an image but at the same time I need to fail the action if I move my finger out while pressing – xmetal Aug 01 '20 at 00:11
  • 1
    @xmetal I think I don't understand what is the problem. When you move your finger more than a minimumDistance you set (100 in the answer above), you can call your code to stop your action instead of printing "Pressed". – pawello2222 Aug 01 '20 at 07:19
  • that’s exactly what I’m trying to do but I don’t know how to stop the printing action – xmetal Aug 01 '20 at 07:53
  • 1
    @xmetal In your code in `.onEnded` you can replace `print("Pressed")` line with whatever you want to do when the gesture ends. – pawello2222 Aug 01 '20 at 07:58
  • Oh okay, I got it. I’m not very familiar with animation but in case I want to print “Pressed” when the gesture doesn’t fail, where should I put it in the code? – xmetal Aug 01 '20 at 08:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219032/discussion-between-xmetal-and-pawello2222). – xmetal Aug 01 '20 at 10:05