skip to content

In SwiftUI, why keep a DragGesture's live offset in @GestureState rather than @State, and what happens when the drag is cancelled?

level: middleimportance: must knowfreq 65%

answer

  1. transient versus committed state
  2. updating writes an inout copy
  3. onEnded only on success
  4. automatic reset to the initial value

basics

~20 s

@GestureState holds a value only while the gesture is active and resets by itself when the gesture ends or is cancelled. Write it in updating(_:body:); commit the final translation to @State in onEnded, which runs only on success.

solid answer

~40 s

A pan has two kinds of state: where the photo **rests** (`@State`, changed when a drag completes) and how far the **current** drag has moved it (`@GestureState`). You pass `$dragOffset` to `updating(_:body:)`, whose closure receives the gesture's value, an `inout` copy of the gesture state and an `inout Transaction`, and you set `state = value.translation`. SwiftUI calls `updating` when it recognises the gesture and on each change, but not when the gesture ends or is cancelled: it resets the property to its initial value instead. `onEnded` runs only when the gesture succeeds, so the final translation is added to the `@State` there. That reset is the point: a `@State` offset set in `onChanged` and cleared in `onEnded` stays stuck when a drag is cancelled, because `onEnded` never runs.

code

swift · 24 lines
swift
import SwiftUI

struct PannablePhoto: View {
    @State private var committed: CGSize = .zero          // survives the gesture
    @GestureState private var dragOffset: CGSize = .zero   // live, resets to .zero

    var body: some View {
        Image(systemName: "photo")
            .resizable()
            .scaledToFit()
            .offset(x: committed.width + dragOffset.width,
                    y: committed.height + dragOffset.height)
            .gesture(
                DragGesture(minimumDistance: 10)
                    .updating($dragOffset) { value, state, _ in
                        state = value.translation
                    }
                    .onEnded { value in
                        committed.width += value.translation.width
                        committed.height += value.translation.height
                    }
            )
    }
}

go deeper

for a junior

Recall that @GestureState is for values that only matter during a gesture and that it resets by itself when the gesture is over.

for a middle

Explain updating, onChanged and onEnded: when each runs, why onEnded runs only on success, and how committed and live offsets add up.

for a senior

Diagnose views stuck mid-drag after interruptions by tracing state cleared only in onEnded, and move it into @GestureState with an animated reset.

for a principal

Treat transient-versus-committed state as a standard for every custom interaction, so interrupted gestures cannot leave screens in half-finished states.

## Two kinds of state in one drag Think of a photo viewer where the user drags a zoomed photo around. At any moment the photo's position is the sum of two numbers: - **Committed offset**: where the photo sat when the last drag finished. It must survive the gesture, so it lives in `@State`. - **Live offset**: how far the finger has moved during the drag in progress. It means nothing once the finger lifts, so it lives in `@GestureState`. `@GestureState` is a property wrapper SwiftUI provides for exactly this second kind. Apple's documentation describes it as a property that updates while the user performs a gesture and resets back to its initial state when the gesture ends, which makes it suitable for tracking **transient state**. ## The three callbacks and what each may touch A gesture reports changes through three methods on the `Gesture` protocol. They differ in when SwiftUI calls them and in what they are for: | Callback | When SwiftUI calls it | Typical use | |---|---|---| | `updating(_:body:)` | when it recognises the gesture and whenever the value changes; not when the gesture ends or is cancelled | write the live value into a `@GestureState` | | `onChanged(_:)` | whenever the value changes (requires an `Equatable` value) | changes that should **not** reset, such as counting attempts | | `onEnded(_:)` | only when the gesture succeeds, with the final value | commit the result to `@State` | The `updating` closure receives three arguments: the gesture's current value, an `inout` copy of the gesture state to write, and an `inout Transaction` you can use to attach an animation to the change. Writing `state = value.translation` is the whole job for a pan. ## How the reset works When the gesture becomes inactive, whether it succeeded or was cancelled, SwiftUI puts the `@GestureState` back to its initial value. Several details follow from that design: 1. **You cannot assign to it from elsewhere.** The wrapped value is get-only; writing `dragOffset = .zero` in a button action fails to compile with *cannot assign to property: 'dragOffset' is a get-only property*. Only the `updating` closure writes it. 2. **The projected value is not a `Binding`.** `$dragOffset` is a `GestureState`, meant for `updating`, not for passing to a child view. 3. **The reset can be animated.** `@GestureState(resetTransaction: Transaction(animation: .spring))` animates the snap back; `init(wrappedValue:reset:)` takes a closure that receives the value and an `inout Transaction` when the reset happens. How animations and transactions behave in general is covered in the lesson on animation triggers. ## Why not plain @State? You can make a drag work with `@State` alone: set a flag or offset in `onChanged`, clear it in `onEnded`. The flaw shows up on the unhappy path. `onEnded` runs only when the gesture succeeds; if the drag is cancelled, for example because another gesture takes over or the system interrupts the touch, the clearing code never runs and the view stays in its mid-drag appearance. `@GestureState` cannot get stuck that way because SwiftUI resets it on every way out of the gesture. ## Worked example: panning a photo ```swift @State private var committed: CGSize = .zero @GestureState private var dragOffset: CGSize = .zero Image(systemName: "photo") .offset(x: committed.width + dragOffset.width, y: committed.height + dragOffset.height) .gesture( DragGesture(minimumDistance: 10) .updating($dragOffset) { value, state, _ in state = value.translation } .onEnded { value in committed.width += value.translation.width committed.height += value.translation.height } ) ``` `DragGesture` starts after the finger has moved `minimumDistance` points (default `10`) and reports locations in its `coordinateSpace` (default `.local`). Its value carries `translation` (total movement since the drag began), `location`, `startLocation`, `velocity` and `predictedEndTranslation`, the last of which is useful for a fling that continues after the finger lifts. ## Mistakes that come up in review - **Adding the translation in `onChanged`.** `translation` is cumulative since the drag began, so adding it on every change counts the same movement many times. - **Committing in the reset closure.** The reset also runs when the drag is cancelled, so a cancelled drag would move the photo. - **Clearing a `@State` drag flag in `onEnded` only.** A cancelled drag leaves the flag set. - **Expecting a final `updating` call with the end value.** SwiftUI does not call `updating` when the gesture ends; read the final value in `onEnded`.

  • How do you make a view spring back smoothly when its @GestureState resets?
    Give the wrapper a reset transaction: `@GestureState(resetTransaction: Transaction(animation: .spring))`. For per-reset control, `init(wrappedValue:reset:)` takes a closure that receives the value and an `inout Transaction` when the reset happens, so you can choose the animation there.
  • Why can't a Cancel button simply set the @GestureState property back to zero?
    The wrapped value of `@GestureState` is get-only outside the gesture. The compiler rejects the assignment with *cannot assign to property: 'offset' is a get-only property*. Only the `updating(_:body:)` closure writes it, through its `inout` state argument, and SwiftUI performs the reset itself.
  • When do you still want onChanged on a drag?
    When a change during the gesture must persist after it ends: counting how many times a long press started, playing a haptic once per threshold crossed, logging. `onChanged(_:)` is available when the gesture's value is `Equatable`, which `DragGesture.Value` is.

Sliding a chess piece: while your hand is on it, its position is tentative (@GestureState). Complete a legal move and you record it on the score sheet (onEnded into @State); if the move is interrupted, the piece simply returns to its square.

  • @GestureState keeps its last value after the finger lifts
  • onEnded runs whenever the gesture stops, cancellations included
  • A Cancel button can reset a @GestureState by assigning to it
  • updating(_:body:) gets one last call with the final value when the drag ends
  • A @State offset cleared in onEnded is just as safe as @GestureState