In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?
answer
- count parameter, default one
- a location-passing overload
- tappable area follows drawn content
- contentShape widens the target
- what Button brings for free
basics
~20 sAttach onTapGesture(count:perform:) to a view to run code on a tap, or on a double tap with count: 2. When the view behaves like a button, use Button instead: it brings the standard button behaviour and accessibility users expect.
solid answer
~40 s`onTapGesture(count:perform:)` runs a closure once the view has been tapped `count` times (default `1`), and an overload hands the closure the tap location as a `CGPoint`. For press-and-hold there is `onLongPressGesture(minimumDuration:maximumDistance:perform:onPressingChanged:)`, whose defaults are 0.5 seconds and 10 points of allowed movement. The tappable area is what the view actually draws, so the empty space a `Spacer` leaves in an `HStack` row ignores taps until you add `.contentShape(Rectangle())`. Apple's documentation is direct about the choice: when you need a button, use `Button`, because it supplies the behaviours users expect from a button, such as accessibility labels and hints. A tap gesture is for interactions that are not buttons: double-tapping a photo, tapping a canvas at a point, a long press that reveals details.
code
swift · 23 linesimport SwiftUI
struct PhotoRow: View {
let title: String
@State private var isFavorite = false
@State private var showsInfo = false
var body: some View {
HStack {
Image(systemName: "photo")
Text(title)
Spacer()
Image(systemName: isFavorite ? "heart.fill" : "heart")
}
.contentShape(Rectangle()) // the gap the Spacer leaves is tappable too
.onTapGesture(count: 2) {
isFavorite.toggle()
}
.onLongPressGesture(minimumDuration: 0.5) {
showsInfo = true
}
}
}go deeper
Know onTapGesture with its count parameter, onLongPressGesture and its two defaults, and why a button-like view should be a Button.
Explain hit testing: why empty stack space ignores taps and how contentShape, placed before the gesture, changes the tappable shape.
In review, catch tap gestures standing in for buttons and say what is lost; pick a tap gesture deliberately for content interactions.
Set a team rule that actions are Buttons with styles and gestures are reserved for content, and make accessibility review part of approving any exception.
## What a tap gesture is in SwiftUI SwiftUI recognises touches through **gestures**: values that conform to the `Gesture` protocol and match a sequence of touch events to a pattern such as a tap, a long press or a drag. You can build a gesture value and attach it with `gesture(_:)`, but for the two most common patterns SwiftUI offers convenience modifiers that do both in one step: - **`onTapGesture(count:perform:)`** runs its closure when the view is tapped `count` times. `count` defaults to `1`; `count: 2` gives a double tap. - **`onTapGesture(count:coordinateSpace:perform:)`** does the same but passes the closure a `CGPoint`: where the finger landed, in the view's local coordinates unless you name another coordinate space. - **`onLongPressGesture(minimumDuration:maximumDistance:perform:onPressingChanged:)`** runs `perform` once a finger has stayed down for `minimumDuration` seconds (default `0.5`) without moving more than `maximumDistance` points (default `10`). The optional `onPressingChanged` closure receives `true` when the press starts and `false` when it ends, which is handy for a pressed highlight. Each convenience modifier has a gesture type behind it that you use when you need to combine or configure gestures: | Convenience modifier | Gesture type | Value it reports | |---|---|---| | `onTapGesture(count:perform:)` | `TapGesture(count:)` | nothing (`Void`) | | `onTapGesture(count:coordinateSpace:perform:)` | `SpatialTapGesture` (iOS 16) | a location | | `onLongPressGesture(...)` | `LongPressGesture(minimumDuration:maximumDistance:)` | a `Bool` | ## Hit testing and contentShape A gesture only receives touches that land inside the view's **hit-testing shape**. By default that shape follows what the view draws. This surprises people with list-like rows: in an `HStack` of an icon, a title, a `Spacer` and a heart, the stretch of empty space the `Spacer` creates draws nothing, so a tap there does not reach the row's `onTapGesture`. The fix is one modifier: - **`contentShape(_:eoFill:)`** defines the shape SwiftUI uses for hit testing. `.contentShape(Rectangle())` makes the row's whole rectangular frame tappable. - `contentShape(_:_:eoFill:)` takes a `ContentShapeKinds` first, so you can change the shape for one purpose only, such as `.interaction`, `.contextMenuPreview` or `.accessibility`. - Place `contentShape` before the gesture modifier, so the gesture is attached to the view whose shape you changed. ## Tap gesture or Button? The most common review comment on tap gestures is not about the gesture at all. Apple's documentation on gestures carries an explicit note: when you need a button, use a `Button` rather than a tap gesture, because the button type automatically provides many of the standard behaviours users expect, such as accessibility labels and hints. The pages for `onTapGesture` add that a control functionally equivalent to a button should be a customised `Button` (through a `ButtonStyle`) rather than a tap gesture. In practice: 1. If tapping the view **performs an action the user would call pressing a button** (save, follow, add to cart), write a `Button` and give it whatever label view you like. 2. If the tap is **a gesture on content** (double-tap to like a photo, tap a point on a chart, long press for a preview), a tap gesture is the right tool. 3. If you keep a tap gesture on something button-like for a good reason, you take on the accessibility work yourself; that work is covered in the lesson on VoiceOver and accessibility traits. ## Worked example: a photo row A row in a photo viewer toggles a favourite on double tap and opens details on a long press. The row is not a button: it is content with gestures on it, so tap gestures fit. `contentShape(Rectangle())` makes the gap around the `Spacer` respond too. ```swift HStack { Image(systemName: "photo") Text(title) Spacer() Image(systemName: isFavorite ? "heart.fill" : "heart") } .contentShape(Rectangle()) .onTapGesture(count: 2) { isFavorite.toggle() } .onLongPressGesture(minimumDuration: 0.5) { showsInfo = true } ``` If the same view also needed a single-tap action, two tap modifiers would compete for the first tap; pairing a single and a double tap is a gesture-composition problem, solved with exclusive composition. ## Mistakes that come up in review - **Expecting the whole row to be tappable.** Without `contentShape`, empty space in a stack is not part of the hit area. - **Rebuilding a button out of `onTapGesture`.** It works for a finger on a screen and loses the behaviours `Button` provides, starting with how assistive technologies announce it. - **Assuming the long press tolerates any movement.** Moving farther than `maximumDistance` (10 points by default) makes the long press fail, and `perform` never runs. - **Assuming `count: 2` also fires on the first tap.** The closure runs once the count is reached, not on every tap along the way.
- How do you find out where on the view the user tapped?Use the overload `onTapGesture(count:coordinateSpace:perform:)`: its closure receives a `CGPoint` in the view's local coordinate space by default. When you need the location as a gesture value you can compose with others, use `SpatialTapGesture`, available since iOS 16, whose value carries a `location`.
- Why does a long press on a row sometimes never fire when the user's finger drifts?`onLongPressGesture` fails once the finger moves farther than `maximumDistance`, which defaults to 10 points, so `perform` does not run. `onPressingChanged` still reports `true` when the press starts and `false` when it ends. Raise `maximumDistance` if the interaction tolerates drift.
- onTapGesture on an HStack makes the whole row tappable, gaps included
- A tap gesture and a Button are the same thing to VoiceOver users
- onTapGesture(count: 2) also runs its action on the first of the two taps
- A long press keeps waiting however far the finger moves