Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Rotating Views with Gestures in SwiftUI
Written by Team Kodeco

Rotating views can add a dynamic and engaging aspect to your app’s user interface. With SwiftUI, it’s easy to add rotation functionality to your views using gestures.

To rotate a view with a gesture, you can use the rotationEffect modifier along with a RotationGesture. In the code below, you have a Rectangle view that can be rotated with a two-finger rotation gesture.

struct ContentView: View {
  @State private var angle: Angle = .degrees(0)
  
  var body: some View {
    Rectangle()
      .fill(Color.blue)
      .frame(width: 100, height: 100)
      .rotationEffect(angle)
      .gesture(RotationGesture()
        .onChanged { angle in
          self.angle = angle
        })
  }
}

Your preview should look like this:

Use rotationEffect and RotationGesture to implement view rotation with a gesture.
Use rotationEffect and RotationGesture to implement view rotation with a gesture.

Note: To test this example in the simulator, move the cursor onto the blue diamond, then press Option to display touch points. Learn more about interacting with the simulator in the Apple documentation here.

In the code above, you first declare a @State property angle that represents the angle of rotation for the view. You start with an initial rotation of 0 degrees.

Next, you create a rectangular view with a blue color, and set its dimensions to a width and height of 100 points. You apply a rotationEffect modifier on the view and pass in the angle property to make it rotate.

To enable the view to be rotated with gestures, you add a gesture modifier and pass in a RotationGesture. This gesture is triggered when the user rotates two fingers on the view. When this gesture is triggered, the onChanged closure is called with an angle parameter that represents the current angle of rotation. You update the angle property with the new angle value, which then updates the rotation of the view via the rotationEffect modifier.

That’s it! With just a few lines of code, you were able to add rotation functionality to a view in SwiftUI using gestures.

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.