Home Guides withAnimation

withAnimation in SwiftUI

withAnimation in SwiftUI wraps a change of state. The views that read that state ease from the old value to the new one. Here, a tap springs a label’s scale.

A sketch of the motion. The file below plays on the phone, and the same source pastes into Xcode.

The file

import SwiftUI

struct SpringLabel: View {
    @State private var on = false

    var body: some View {
        Button {
            withAnimation(.spring(response: 0.35, dampingFraction: 0.55)) {
                on.toggle()
            }
        } label: {
            Text(on ? "On" : "Off")
                .font(.title)
                .foregroundStyle(.white)
                .padding(22)
                .background(.orange, in: RoundedRectangle(cornerRadius: 16))
                .scaleEffect(on ? 1.12 : 1)
        }
        .buttonStyle(.plain)
    }
}

The button takes two closures. The first runs on the tap. The second, label:, is what you see. Inside the action, on.toggle() flips the @State bool, and withAnimation tells SwiftUI to interpolate. scaleEffect reads on, so the scale is what moves. The text swaps with it.

.spring(response: 0.35, dampingFraction: 0.55) is a short spring with a little overshoot. A higher damping fraction settles with less bounce. .buttonStyle(.plain) drops the system button chrome so the orange shape is the control.

What it will not do

It will not keep spinning. When on has finished changing, the spring is done. Continuous motion belongs on a timeline. A move that should happen once, as the view arrives, belongs in onAppear.

Keep going

Get Swoop

iPhone. iOS 17 and later. The file plays on the phone.