Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Animate a View's Rotation in SwiftUI
Written by Team Kodeco

Animating a view’s rotation in SwiftUI can be an exciting way to bring a touch of dynamism and visual flair to your user interface. You can use the rotation3DEffect modifier to animate a view’s rotation.

See how this works in this rotating button example:

struct ContentView: View {
  @State private var rotate = false

  var body: some View {
    VStack {
      Button(action: {
        rotate.toggle()
      }) {
        Text("Rotate")
          .font(.title)
          .fontWeight(.bold)
          .foregroundColor(.white)
          .padding()
          .background(.blue)
          .cornerRadius(10)
      }
      .rotation3DEffect(.degrees(rotate ? 180 : 0), axis: (x: 0, y: 1, z: 0))
      .animation(.easeInOut(duration: 0.5), value: rotate)
    }
  }
}

Your preview should look like this:

Use the rotation3Deffect and animation modifiers to animate a view's rotation.
Use the rotation3Deffect and animation modifiers to animate a view's rotation.

In this example, you use the @State property wrapper to manage the rotation state, meaning whether or not the button should rotate. When the button is tapped, this toggles the rotate state.

You use the rotation3DEffect modifier to determine the button’s rotation. The ternary operator is used to decide whether the button should rotate 180 degrees (when rotate is true) or remain in its original position (when rotate is false).

To animate this rotation, you use the animation modifier, indicating an easeInOut timing curve with a duration of 0.5 seconds. This means that the button will execute a smooth rotation around its y-axis over the course of half a second. The value parameter in the animation ensures the animation takes place whenever the rotate state changes.

And that’s it! You’re encouraged to experiment with different values for the rotation degree, timing curve and duration to achieve a variety of animation effects. Combining this with other animation techniques can give rise to captivating and dynamic user interfaces.

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.