Skip to main content

How to create gesture chains using sequenced(before)

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create gesture chains using sequenced(before) 관련

SwiftUI by Example

Back to Home

How to create gesture chains using sequenced(before:) | SwiftUI by Example

How to create gesture chains using sequenced(before:)

Updated for Xcode 15

SwiftUI lets us create new gestures out of sequences of other gestures, which allows us to trigger an action only when two gestures occur back to back – for example if the user drags a view then long-presses on it.

Because the sequenced views need to be able to reference each other, you can't really create them as properties of your view. Instead, create them directly inside your body property, then use firstGesture.sequenced(before: secondGesture) to chain the two together into a single gesture.

As an example, this next code requires you to long press on the text view before dragging it:

struct ContentView: View {
    @State private var message = "Long press then drag"

    var body: some View {
        let longPress = LongPressGesture()
            .onEnded { _ in
                message = "Now drag me"
            }

        let drag = DragGesture()
            .onEnded { _ in
                message = "Success!"
            }

        let combined = longPress.sequenced(before: drag)

        Text(message)
            .gesture(combined)
    }
}

Download this as an Xcode projectopen in new window

As you can see, I've made the text view update as the two gestures happen, so if you try it out you'll be able to follow the progress of the gesture sequence.

Similar solutions…
How to add a gesture recognizer to a view | SwiftUI by Example

How to add a gesture recognizer to a view
How to force one gesture to recognize before another using highPriorityGesture() | SwiftUI by Example

How to force one gesture to recognize before another using highPriorityGesture()
How to create multi-column lists using Table | SwiftUI by Example

How to create multi-column lists using Table
What is the @GestureState property wrapper? | SwiftUI by Example

What is the @GestureState property wrapper?
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared

이찬희 (MarkiiimarK)
Never Stop Learning.