39

SwiftUI Spring Animation Tutorial

 4 years ago
source link: https://www.ioscreator.com/tutorials/swiftui-spring-animation-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.

Spring animations simulates "springy" motions. The animated object will move to a new location and then jiggles before setting into place. In this tutorial a rectangle will rotate with a spring animation .SwiftUI requires Xcode 11 and MacOS Catalina, 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 the Single View App template, and then click Next . Enter SwiftUISpringAnimationTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

JNNzuiQ.png!web

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

QF3Ibe3.png!web

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

struct ContentView: View {
    
    // 1.
    @State private var rotatingAngle: Double = 0
    
    var body: some View {
        // 2.
        Button(action: {
            self.rotatingAngle += 90
        }) {
             // 3.
             Rectangle()
                .fill(Color.red)
                .frame(width: 200, height: 200)
                .rotationEffect(.degrees(rotatingAngle))
                // 4.
                .animation(.interpolatingSpring(mass: 1, stiffness: 1, damping: 0.5, initialVelocity: 1))
        }
    }
}
  1. Declare the state property to keep track of the rotating angle.

  2. Display a button, when clicked the rotating angle will increment with 90 degrees.

  3. Display a red rectangle which will rotate with the current rotating angle.

  4. The spring animation which has the following parameters: the mass of the object, the stiffness of the spring, how fast the springiness slows down, and how fast the springiness starts moving at the start.

Go to the preview pane and select the live preview button. Click the rectangle to start the spring animation.

imAVBrF.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK