8

SwiftUI 3D Rotation Tutorial

 3 years ago
source link: https://www.ioscreator.com/tutorials/swiftui-3d-rotation-tutorial
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
SwiftUI 3D Rotation Tutorial

The rotation3DEffect modifier rotates a view in 3D. The angle of the rotation can be set by the degrees parameter. In this tutorial a button will be rotated on the X-, Y- or Z-axis using Toggle Views. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.

Enter SwiftUI3DRotationTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbox and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View { // 1. @State private var degrees = 0.0 // 2. @State private var rotateX = true @State private var rotateY = true @State private var rotateZ = true var body: some View { VStack(spacing: 30) { // 3. Toggle("Rotate X-axis", isOn: $rotateX) Toggle("Rotate Y-axis", isOn: $rotateY) Toggle("Rotate Z-axis", isOn: $rotateZ) // 4. Button("Hello World") { withAnimation(.easeIn(duration: 1)) { self.degrees += 360 } } .padding(20) .background(Color.red) .foregroundColor(Color.white) // 5. .rotation3DEffect(.degrees(degrees), axis: (x: rotateX ? 1 : 0, y: rotateY ? 1 : 0, z: rotateZ ? 1 : 0)) Spacer() } .padding() } }
  1. a State properties is declared which holds the angle of the rotation

  2. Three boolean state properties are declared which holds the state of the rotation of the corresponding axis.

  3. The Toggles are displayed which can turn on and off the rotation of the axes.

  4. The button will be animated with 360 degrees.

  5. The rotation3DEffect modifier rotates the view in the axes which are turned on. in the toggles.

Go to the Preview and switch the toggles to select the axes. Press the “Hello Wordl” button to view the animation.

The source code of the SwiftUI3DRotationTutorial can be downloaded at the ioscreator repository on Github.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK