Use gesture modifiers to add interactivity to your app.
Gesture modifiers handle all of the logic needed to process user-input events such as touches, and recognize when those events match a known gesture pattern, such as a long press or rotation. When recognizing a pattern, SwiftUI runs a callback you use to update the state of a view or perform an action.
Add Gesture Modifiers to a View
Each gesture you add applies to a specific view in the view hierarchy. To recognize a gesture event on a particular view, create and configure the gesture, and then use the gesture(_:including:) modifier:
Respond to Gesture Callbacks
Depending on the callbacks you add to a gesture modifier, SwiftUI reports back to your code whenever the state of the gesture changes. Gesture modifiers offer three ways to receive updates: updating(_:body:),
Update Transient UI State
To update a view as a gesture changes, add a
Gesture property to your view and update it in the
updating(_: callback. SwiftUI invokes the updating callback as soon as it recognizes the gesture and whenever the value of the gesture changes. For example, SwiftUI invokes the updating callback as soon as a magnification gesture begins and then again whenever the magnification value changes. SwiftUI doesn’t invoke the updating callback when the user ends or cancels a gesture. Instead, the gesture state property automatically resets its state back to its initial value.
For example, to make a view that changes color while the user performs a long press, add a gesture state property and update it in the
Update Permanent State During a Gesture
To track changes to a gesture that shouldn’t reset once the gesture ends, use the
on callback. For example, to count the number of times your app recognizes a long press, add an
on callback and increment a counter.
Update Permanent State When a Gesture Ends
To recognize when a gesture successfully completes and to retrieve the gesture’s final value, use the
on function to update your app’s state in the callback. SwiftUI only invokes the
on callback when the gesture succeeds. For example, during a
Long if the user stops touching the view before
minimum seconds have elapsed or moves their finger more than
maximum points SwiftUI does not invoke the
For example, to stop counting long press attempts after the user completes a long press, add an
on callback and conditionally apply the gesture modifier.