article

Friday, August 6, 2021

SwiftUI 3D Rotation - rotation3DEffect

SwiftUI 3D Rotation - rotation3DEffect


The rotation3DEffect modifier rotates a view in 3D. The angle of the rotation can be set by the degrees parameter.

ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//
 
import SwiftUI
 
struct ContentView: View {
    @State private var degrees = 0.0
    @State private var rotateX = true
    @State private var rotateY = true
    @State private var rotateZ = true
     
    var body: some View {
         
        VStack(spacing: 30) {
            Toggle("Rotate X-axis", isOn: $rotateX)
            Toggle("Rotate Y-axis", isOn: $rotateY)
            Toggle("Rotate Z-axis", isOn: $rotateZ)
 
            Button("3D Rotation - rotation3DEffect") {
                withAnimation(.easeIn(duration: 1)) {
                    self.degrees += 360
                }
            }
            .padding(20)
            .background(Color.green)
            .foregroundColor(Color.white)
 
            .rotation3DEffect(.degrees(degrees), axis: (x: rotateX ? 1 : 0, y: rotateY ? 1 : 0, z: rotateZ ? 1 : 0))
             
            Spacer()
        }
        .padding()
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post