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:
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.