
Responding to gestures: Magnifying
Learn how to implement magnify gestures in your SwiftUI app to allow users to zoom in and out of content with intuitive pinch controls
To implement gestures that recognize a magnifying motion in SwiftUI, use the MagnifyGesture
. Also known as a pitch-to-zoom feature, it’s the type of gesture that allows users to zoom in and out on content using pinch controls.
MagnifyGesture(minimumScaleDelta: 0.05)
The property minimumScaleDelta
defines a minimum required delta for the gesture to be activated.
When using the gesture to set up a magnification factor, we can take advantage of the @GestureState
property wrapper for updating a property associated with that gesture while the user performs it. Once the gesture ends, the property resets to its initial state.
struct ContentView: View {
@GestureState var pinchScale = 1.0
var magnifyGesture: some Gesture {
MagnifyGesture(minimumScaleDelta: 0.05)
.updating($pinchScale) { value, gestureState, _ in
gestureState = value.magnification
}
}
var body: some View {
ZStack {
VStack {
Spacer()
Text("x") + Text(pinchScale, format: .number.precision(.fractionLength(2)))
}
Image(systemName: "star.fill")
.font(.system(size: 100))
.scaleEffect(pinchScale)
.gesture(magnifyGesture)
}
}
}
The magnifying gesture is set with the gesture(_:including:)
modifier on the view, which should respond to it.
In the example, the scaleEffect(_:anchor:)
modifier uses the updated value of the pinchScale
property to increase or decrease the size of the view.
Refer to the Gestures section of the Apple Human Interface Guidelines for guidance on when to apply gestures, such as pinch-to-zoom, effectively across Apple platforms.
