Rotating Views Along Any Axis in SwiftUI
Animations in your UI are a must these days, but everyone is doing the same old fade or move animations. If you really want to take your animations to the next level you need to incorporate some rotation.
There are two main modifiers for handling rotation of a View in SwiftUI:
.rotationEffect
.rotation3DEffect
The first one, rotationEffect
, locks you into rotating a View along the Z axis, like in the gif above. That’s probably the one you want to go with for the majority of your rotations. But maybe you’re building something like a storybook app and you want the pages to flip along the Y axis. That’s where rotation3DEffect
comes in.
Let’s take a look at the code for rotating a rectangle along the Z axis, like in the gif above:
@State private var degrees: Double = 0.0
private let animation = Animation.linear(duration: 0.75).repeatForever(autoreverses: false)
var body: some View {
VStack(spacing: 50) {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.red)
.rotation3DEffect(Angle(degrees: degrees), axis: (x: 0, y: 0, z: 1))
.animation(animation)
Button(action: {
self.degrees += 180
}) {
Text("Rotate")
}
}
}
What’s happening here is when you tap the button the degrees
property is increased by 180, telling our view to rotate 180 degrees. The animation being used is set to repeat forever, essentially looping the rotation.
Taking a closer look at the rotation3DEffect
modifier you’ll see that there’s a parameter for the axis of rotation. Each of the axes takes a value between 0 and 1 to determine how to rotate your view. In our case, the only axis we want to rotate around is the Z axis so that is set to 1 and the rest are set to 0. Now all you would need to do is change that to have the y axis set to 1 and the others set to 0 to get that page-flip animation.
.rotation3DEffect(Angle(degrees: degrees), axis: (x: 0, y: 1, z: 0))