SwiftUI Animations Spring Animations

SwiftUI Animations: Spring Animations

Use .spring() animations to simulate mass-spring-damper motion with configurable stiffness and damping.


Syntax

Spring: withAnimation(.spring(response: 0.4, dampingFraction: 0.6)) { state.toggle() }response controls speed, dampingFraction controls overshoot/bounce.


Basic Spring Toggle

Tap the button to toggle the circle’s size with a spring animation configured by response and dampingFraction.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SpringDemo: View {
  @State private var on = false
  var body: some View {
VStack(spacing: 12) {
  Circle()
    .fill(on ? .green : .gray)
    .frame(width: on ? 120 : 60, height: on ? 120 : 60)
  Button("Toggle") {
    withAnimation(.spring(response: 0.4, dampingFraction: 0.6)) { on.toggle() }
  }
}
.padding()
} }


Tuned Spring Parameters

Experiment with a bouncier spring by lowering damping and changing response. Multiple shapes animate with different timing.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SpringTunedDemo: View {
  @State private var on = false
  var body: some View {
VStack(spacing: 16) {
  RoundedRectangle(cornerRadius: 12)
    .fill(.blue.opacity(0.2))
    .frame(width: on ? 220 : 140, height: 40)
    .animation(.spring(response: 0.25, dampingFraction: 0.45), value: on)
  Circle()
    .fill(.orange.opacity(0.4))
    .frame(width: on ? 80 : 40, height: on ? 80 : 40)
    .animation(.spring(response: 0.5, dampingFraction: 0.65), value: on)
  Button(on ? "Reset" : "Bounce") { on.toggle() }
}
.padding()
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *