SwiftUI Gestures TapGesture
SwiftUI Gestures: TapGesture
React to taps using .onTapGesture or TapGesture().
Syntax
Tap handler: .onTapGesture { ... } or TapGesture().onEnded { ... } to run code when tapped.
Tap to Toggle Color
Tapping the circle toggles a boolean and updates its fill color.
Example
import SwiftUI
struct TapDemo: View {
@State private var on = false
var body: some View {
VStack(spacing: 12) {
Circle()
.fill(on ? .green : .gray)
.frame(width: 80, height: 80)
.onTapGesture { on.toggle() }
Text(on ? "On" : "Off")
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { TapDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the circle toggles color on tap using .onTapGesture.
Double Tap Counter
Use TapGesture(count: 2) to increment a counter only on double-tap.
Example
import SwiftUI
struct DoubleTapDemo: View {
@State private var count = 0
var body: some View {
VStack(spacing: 12) {
Text("Double taps: \(count)")
RoundedRectangle(cornerRadius: 8)
.fill(.blue.opacity(0.15))
.frame(width: 160, height: 80)
.overlay(Text("Double tap me"))
.gesture(TapGesture(count: 2).onEnded { count += 1 })
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DoubleTapDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the counter increments only on double-tap using .onTapGesture(count: 2).