Rotate View in 3D Space with SwiftUI

DevTechie Inc
Jun 11, 2022

SwiftUI’s .rotation3DEffect makes it easy to rotate views in X, Y and Z space. Combining rotation effect with animation looks even cooler.

Let’s work on an example where we will rotate a rounded rectangle in X, Y or/and Z direction.

We will start with rotation on x-axis. We will also need degree State variable so we can apply degree rotation to the axis.

Let’s create a Toggle which will control flag called “rorateX” for rotation in x-axis.

struct RotationExample: View {
    @State private var degree = 0.0
    @State private var rotateX = true
    
    var body: some View {
        VStack {
            Toggle("Rotate X", isOn: $rotateX)
            
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.orange)
                .overlay(Text("DevTechie.com").font(.title))
                .frame(width: 300, height: 100)
                .foregroundColor(.white)
                .rotation3DEffect(.degrees(degree), axis: (x: rotateX ? 1 : 0, y:  0, z:  0))
                .animation(.easeInOut(duration: 2), value: degree)
            
            Button("Rotate") {
                degree += 360
            }
            .padding()
            
        }.padding()
    }
}
Now that we have our view rotating in x-axis, we can adjust the same view to support rotation on Y and Z axis as well.

We will add two more State variables along with two Toggles to control X and Y rotations. Newly added code is shown in bold text below.

struct RotationExample: View {
    @State private var degree = 0.0
    @State private var rotateX = true
    @State private var rotateY = true
    @State private var rotateZ = true
    
    var body: some View {
        VStack {
            Toggle("Rotate X", isOn: $rotateX)
            Toggle("Rotate Y", isOn: $rotateY)
            Toggle("Rotate Z", isOn: $rotateZ)
            
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.orange)
                .overlay(Text("DevTechie.com").font(.title))
                .frame(width: 300, height: 100)
                .foregroundColor(.white)
                .rotation3DEffect(.degrees(degree), axis: (x: rotateX ? 1 : 0, y: rotateY ? 1 : 0, z: rotateZ ? 1 : 0))
                .animation(.easeInOut(duration: 2), value: degree)
            
            Button("Rotate") {
                degree += 360
            }
            .padding()
            
        }.padding()
    }
}

With that, we have reached the end of this article. Hope you enjoyed it. Don’t forgot to subscribe our newsletter.