Simultaneous Gestures in SwiftUI
Written by Team Kodeco
Interactivity is an essential aspect of any application. SwiftUI equips us with a wide array of tools to create engaging and interactive user experiences. Among these are gestures, which allow users to interact with your app in intuitive and natural ways.
In certain scenarios, you may want a single view to respond to multiple gestures simultaneously. For instance, a user might want to rotate an image while also being able to zoom in or out. This is where the simultaneously
modifier comes into play, allowing two gestures to occur at the same time.
Let’s delve into an example where a user can simultaneously rotate and zoom an image:
struct ContentView: View {
@GestureState private var rotationAngle = Angle.zero
@GestureState private var zoomScale = CGFloat(1.0)
var body: some View {
let rotationGesture = RotationGesture()
.updating($rotationAngle) { value, state, _ in
state = value
}
let magnificationGesture = MagnificationGesture()
.updating($zoomScale) { value, state, _ in
state = value
}
let combinedGesture = rotationGesture.simultaneously(with: magnificationGesture)
return Image(systemName: "sun.max.fill")
.resizable()
.scaledToFit()
.frame(width: 200)
.rotationEffect(rotationAngle)
.scaleEffect(zoomScale)
.gesture(combinedGesture)
.foregroundColor(.yellow)
}
}
Here’s what your preview should look like:
In this example:
- A
RotationGesture
updates therotationAngle
state as the user rotates their fingers on the screen. - A
MagnificationGesture
updates thezoomScale
state as the user performs a pinch-to-zoom gesture. - The
simultaneously
modifier combines the rotation and magnification gestures, enabling the user to rotate and zoom the image at the same time.
As the user interacts with the image, SwiftUI updates the rotation and scale in real time, providing a smooth and immersive experience.
In summary, SwiftUI’s gesture system is powerful and flexible. It lets you create rich, interactive experiences tailored to your app’s needs. Don’t hesitate to experiment with this system and craft even more engaging user interactions!