Implementing Pinch to Zoom in SwiftUI
Written by Team Kodeco
When creating user interfaces, it’s important to provide ways for users to interact with your app beyond just tapping. One way to do this is through zooming in and out on your views. In SwiftUI, you can easily add zooming functionality to your app using gestures.
To create zooming gestures in SwiftUI, you can use the MagnificationGesture
modifier. This modifier takes in a closure that is called with a MagnificationGesture.Value
when the user performs the gesture.
Here’s an example of how to use MagnificationGesture
to zoom a view:
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image(systemName: "star.circle.fill")
.resizable()
.scaledToFit()
.scaleEffect(scale)
.gesture(
MagnificationGesture()
.onChanged { value in
self.scale = value.magnitude
}
)
}
}
Your preview should look like this:
Note: To test this example in the simulator, move the cursor onto the star, then press Option to display touch points. Learn more about interacting with the simulator in the Apple documentation here.
In this example, you create a view that displays an image of a star. You use the scaleEffect
modifier to adjust the view’s scale based on the value of the scale
state variable.
You then add a gesture
modifier with a MagnificationGesture
instance. You set the onChanged
closure to update the scale
variable with the magnitude of the gesture. The magnitude
is a CGFloat
that represents the scale factor of the gesture, with 1.0 being the default, unzoomed size.
After adding the gesture, the user will be able to zoom in and out on the image by performing the pinch gesture. The onChanged
closure updates the scale
variable as the user zooms, causing the image’s scale to change in real time.
That’s all it takes to add zooming functionality to your views with gestures in SwiftUI! With these simple steps, you can create a more interactive and engaging user experience in your app.