Create a Spring Animation in SwiftUI
Written by Team Kodeco
Animations are a crucial component when it comes to designing user interfaces, offering both visual appeal and dynamic interactivity. In SwiftUI, you have the ability to create a spring animation, lending your views a lively, bouncy aesthetic. This spring animation can be applied to any animatable property in SwiftUI, such as position, dimensions or rotation.
To generate a spring animation in SwiftUI, you use the .spring()
function, accessible via the animation
modifier.
Let’s illustrate this by applying a spring animation to the rotation of a rectangle view:
struct ContentView: View {
@State private var angle: Double = 0.0
var body: some View {
Rectangle()
.foregroundColor(.blue)
.frame(width: 150, height: 150)
.rotationEffect(.degrees(angle))
.onTapGesture {
angle += 360
}
.animation(.spring(response: 0.5, dampingFraction: 0.4), value: angle)
}
}
Your preview should look like this. Tap the rectangle to see the exciting part:
In the above code, the @State
property wrapper is used to declare a state variable angle
that holds the current rotation angle. You then attach a tap gesture to the rectangle view. When triggered, this increases the angle
by 360 degrees.
Lastly, you apply the .spring()
function to the animation
modifier of the rectangle view. This results in a smooth rotation animation with a spring-like effect whenever the angle
value changes.
You can customize your spring animation by providing parameters to the .spring()
function. In this example, the response
parameter is set to 0.5
, which dictates how quickly the animation begins in seconds, and the dampingFraction
is set to 0.4
, which controls the level of bounciness in the spring effect.
By tweaking these parameters, you can construct spring animations that are ideally suited to your specific requirements.