Detecting Taps in SwiftUI
Written by Team Kodeco
In SwiftUI, recognizing gestures such as taps is straightforward thanks to built-in gesture modifiers. This SwiftUI cookbook entry covers how to detect a tap gesture and how to trigger an action when a tap is recognized.
To illustrate this, you’ll create a simple SwiftUI view that mimics a rocket launch countdown, which decreases with every tap.
struct ContentView: View {
@State private var countdown = 10
var body: some View {
VStack {
Image(systemName: "arrowtriangle.up.fill")
.resizable()
.frame(width: 100, height: 100)
.foregroundStyle(.orange.gradient)
Text("\(countdown) until launch")
.padding()
}
.onTapGesture {
if self.countdown > 0 {
self.countdown -= 1
}
}
}
}
Your preview should look like this:
Here, a VStack
is created containing an image depicting a rocket (using an SF Symbol) and a text displaying the launch countdown. The image is resizable and framed to a specific width and height, and styled with an orange gradient.
The onTapGesture
modifier is added to the VStack
. This means that a tap anywhere within the VStack
will trigger the action in the closure. The closure is the code within the curly brackets {}
following the onTapGesture
modifier.
Inside the closure, you check if the countdown
value is more than zero, and if so, decrement it by 1. This effectively creates a countdown that decreases each time the VStack
is tapped.
In conclusion, SwiftUI’s .onTapGesture
modifier is a simple and powerful tool for detecting and handling tap gestures, enabling you to create more interactive views with minimal code.