TechnologiesSwiftUI

MagnifyGesture struct

iOSmacOStvOSwatchOSvisionOS✓ renders

A gesture that recognizes a magnification motion and tracks the amount of

How it works

A MagnifyGesture recognizes a pinch — the two-finger spread or squeeze that people use to zoom in and out. Attach it to a view to track the relative scaling of the pinch and drive your own resizing, zooming, or scale-effect behavior. Reach for it whenever a view should respond to pinch-to-zoom rather than the discrete taps and drags handled by other gesture types.

  1. Create the gesture and attach it with gesture(_:)

    Instantiate MagnifyGesture() and hand it to a view's .gesture modifier so the view begins watching for pinches. In the example the gesture is attached to the Image, making that view the recognizer's target.

  2. Read the running scale from value.magnification

    As the pinch proceeds, the gesture reports a MagnifyGesture.Value whose magnification property is the scale relative to the start of the pinch — 1.0 means no change, values above 1 mean the fingers spread apart, below 1 mean they pinched together. The example assigns value.magnification straight into the scale state.

  3. Respond live with onChanged(_:)

    Use .onChanged to receive the gesture value continuously while the fingers move, so the view updates in real time. Here onChanged feeds value.magnification into scale, which .scaleEffect(scale) applies to keep the Image sized to the current pinch.

  4. Finish up with onEnded(_:)

    .onEnded fires once when the fingers lift, the place to commit, clamp, or reset the value. The example ignores the final value and resets scale = 1.0, snapping the image back to its original size when the pinch completes.

Try it — In onEnded, replace scale = 1.0 with scale = value.magnification (and accept the value instead of _) so the image keeps the pinched size instead of springing back.

Example & preview

Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.

MagnifyGesture.swift
struct MagnifyGestureDemo: View {
    @State private var scale: CGFloat = 1.0

    var body: some View {
        Image(systemName: "photo")
            .font(.system(size: 80))
            .foregroundStyle(.blue)
            .scaleEffect(scale)
            .gesture(
                MagnifyGesture()
                    .onChanged { value in
                        scale = value.magnification
                    }
                    .onEnded { _ in
                        scale = 1.0
                    }
            )
            .padding()
    }
}
Live preview
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →