Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Use simultaneously(with:) to combine gestures in SwiftUI.
Use simultaneously(with:) to combine gestures in SwiftUI.

In this example:

  1. A RotationGesture updates the rotationAngle state as the user rotates their fingers on the screen.
  2. A MagnificationGesture updates the zoomScale state as the user performs a pinch-to-zoom gesture.
  3. 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!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.