Detect tap and double-tap gestures in SwiftUI

In this tutorial, we will see how to detect tap and double-tap gestures in SwiftUI.

We can use onTapGesture modifier to handle taps on Views. We can attach tap actions to any view using this modifier. The count parameter in this modifier is used to determine the number of taps needed to start the action.

Now, follow the approaches below to achieve the task.

Single tap gesture

First of all, I will create a simple Text view and apply the onTapGesture modifier to that Text view to detect a tap gesture.

This will be a simple Text view that will respond to a single tap.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Tap Here!")
            
            //To add tap gesture
            .onTapGesture {
                print("Tapped!")
            }
    }
}

In the above program, I have used the onTapGesture modifier without any parameters to add a single tap.

So, when we tap on the text view, it will print the message “Tapped” in the console.

Output:

Single tap gesture

Double tap gesture

Now, we can handle the double-tap gesture using the count parameter by passing 2 into this parameter. That means we have to double-tap the Text view to trigger the action.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Tap Here!")
            
            //To add double tap gesture
            .onTapGesture(count: 2) {
                print("Double Tapped!")
            }
    }
}

In the above code, the count: 2  will specify that the action should be triggered only when the Text view is tapped twice.

Output:

Double tap gesture

Leave a Reply

Your email address will not be published. Required fields are marked *