onTapGesture in SwiftUI


SwiftUI comes with a number of gestures to make our life easy by taking care of all the hard work for us. The most common and widely used gesture is onTapGesture. In this tutorial, I am going to let you know all about the onTapGesture modifier with step-by-step examples.

The onTapGesture modifier in SwiftUI adds an action to perform when this view recognizes a tap gesture. In simple words, you can run a piece of your code when someone taps on the view where the onTapGesture is attached.

Suppose, you have a Text view in SwiftUI and you want to run some code on tapping the text view. In this case, you can use the onTapGesture modifier to detect the tap gesture and run the code. Below is given an example:

        Text("Hello World")
            .onTapGesture {
                print("The gesture tapped")
            }

The above SwiftUI code will create a Text view. When we tap or click the text, it will print the message “The gesture tapped” in the terminal.

Syntax of the onTapGesture modifier

Below is given the syntax declaration of onTapGesture in SwiftUI:

func onTapGesture(
    count: Int = 1,
    perform action: @escaping () -> Void
) -> some View

Let’s learn about the parameters in the above syntax

  • count
    This is the number of total taps or clicks required in order to trigger the action closure. The default value of the count is 1.
  • action
    The action to be performed.

onTapGesture with the count value provided

The first example doesn’t have the count value provided. So it was 1 by default. However, you can provide the value for the count parameter in onTapGesture. Here is given the example:

        Text("Hello World")
            .onTapGesture(count: 2) {
                print("The gesture tapped")
            }

This time, you have to tap twice to trigger the action.

You can use onTapGesture for any view

In the same way, you can use the onTapGesture modifier for any other views. For example, you can use it for a circle:

        Circle()
            .fill(.green)
            .onTapGesture {
                print("Gesture tapped")
            }