2

In the following example if only the long press will be performed, there is (apparently) no (built-in) way to find out that the drag gesture had failed (if I just lift my finger off the screen for example)

Is there a way to detect wether the second gesture had failed or hasn't been started?

.gesture(
    LongPressGesture()
        .onEnded { _ in
            // First gesture completed ...
        }
        .sequenced(
            before:
                DragGesture()
                    .onEnded { gesture in
                        // Second gesture ended (not called if it has failed) ...
                    }
        )
        .onEnded { _ in
           // Only called if both gestures succeed...
        }
)
1
  • Perhaps you could consider a position check to see whether the objects was moved your minimum desired distance Commented Jan 30 at 13:25

1 Answer 1

2

You can use exclusively(before:) to achieve this effect. If you have A.exclusively(before: B), then SwiftUI will try to recognise gesture B only if A fails.

In this case, A would be the long press + drag gesture, and B would be just the long press gesture. If B is triggered, that means there is a long press but A failed, which implies that it is the drag gesture that failed.

.gesture(
    LongPressGesture()
        .onEnded { _ in
            print("Long press completed")
        }
        .sequenced(
            before: DragGesture()
                .onEnded { gesture in
                    print("Drag completed")
                }
        )
        .onEnded { x in
            print("Both completed")
        }
        .exclusively(
            before: LongPressGesture()
                .onEnded { _ in print("Drag failed") }
        )
)
Sign up to request clarification or add additional context in comments.

1 Comment

Quite an elegant solution but since the DragGesture fails in my case, I've applied the "exclusively" gesture to it and now it all works and makes sense. Thank you! P.S. SwiftUI should provide a onCanceled handler like UIKit does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.