SwiftUI Animations - 3D Rotation Effect

SwiftUI has lots of new features with the easiest way of implementation. In this tutorial, you’ll learn how to add fancy 3D animations with SwiftUI.

Ashish Kakkad
2 min readJan 29, 2020

rotation3DEffect

The rotation3DEffect() modifier gives output like as rotating views in 3D.

This modifier has two parameters:

angle: for rotate view in specified angle/degrees
axis: for X, Y and Z axis to perform rotation.

For Example:

Text(“SwiftUI Animations”)
.rotation3DEffect(.degrees(45), axis: (x: 1, y: 0, z: 0))

Let’s Do It With Animation

Now we will create one button with a rotating view by 3D Effect.

Button("Animate..!") {
withAnimation {
self.degrees += 360
}
}
.padding(20)
.background(Color.blue.opacity(0.8))
.foregroundColor(Color.white)
.rotation3DEffect(.degrees(degrees), axis: (x: 1, y: 1, z: 1))

Here, degrees variable is defined as @State so when that value changes, it automatically performs the 3D rotation effect.

Put All Together:

//
// ContentView.swift
//
// Created by Ashish Kakkad on 29/01/2020.
//

import SwiftUI
struct ContentView: View {
@State private var degrees = 0.0

var body: some View {
VStack {
Button("Animate..!") {
withAnimation {
self.degrees += 360
}
}
.padding(20)
.background(Color.blue.opacity(0.8))
.foregroundColor(Color.white)
.rotation3DEffect(.degrees(degrees), axis: (x: 1, y: 1, z: 1))
Text("SwiftUI Animations")
.rotation3DEffect(.degrees(45), axis: (x: 1, y: 0, z: 0))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Conclusion

SwiftUI is coming with lot of things to learn. Keep Learning!
Happy Coding 🙂

Originally published at https://ashishkakkad.com on January 29, 2020.

--

--