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.
Create the gesture and attach it with gesture(_:)
Instantiate
MagnifyGesture()and hand it to a view's.gesturemodifier so the view begins watching for pinches. In the example the gesture is attached to theImage, making that view the recognizer's target.Read the running scale from value.magnification
As the pinch proceeds, the gesture reports a
MagnifyGesture.Valuewhosemagnificationproperty 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 assignsvalue.magnificationstraight into thescalestate.Respond live with onChanged(_:)
Use
.onChangedto receive the gesture value continuously while the fingers move, so the view updates in real time. HereonChangedfeedsvalue.magnificationintoscale, which.scaleEffect(scale)applies to keep theImagesized to the current pinch.Finish up with onEnded(_:)
.onEndedfires once when the fingers lift, the place to commit, clamp, or reset the value. The example ignores the final value and resetsscale = 1.0, snapping the image back to its original size when the pinch completes.
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.
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()
}
}