SwiftUI Animations

SwiftUI Animations

SwiftUI makes animating your user interface shockingly easy.

Instead of calculating frames and durations manually, you simply tell SwiftUI what state should change, and it automatically interpolates the transition for you.

There are two main ways to animate views in SwiftUI: Explicit animations and Implicit animations.


Explicit Animations (withAnimation)

Explicit animations are triggered by wrapping a state change inside a withAnimation block.

This tells SwiftUI that any views affected by this specific state change should animate to their new values.

Explicit Animation:

import SwiftUI

struct ScaleButton: View { @State private var isScaled = false var body: some View { Button("Press Me") { // The state change is wrapped in withAnimation withAnimation(.spring()) { isScaled.toggle() } } .padding() .background(Color.blue) .foregroundColor(.white) // The scale effect reacts to the animated state change .scaleEffect(isScaled ? 1.5 : 1.0) } }


Implicit Animations (.animation)

Implicit animations are added directly to a view using the .animation() modifier.

This tells the view: "Any time the specified value changes, animate the change."

Implicit Animation:

struct RotateIcon: View {
    @State private var degrees = 0.0
    var body: some View {
        Image(systemName: "arrow.2.circlepath")
            .font(.largeTitle)
            .rotationEffect(.degrees(degrees))
            // The view will automatically animate whenever 'degrees' changes
            .animation(.easeInOut(duration: 1.0), value: degrees)
            .onTapGesture {
                degrees += 180
            }
    }
}

Animation Types

SwiftUI provides numerous built-in animation curves to make your app feel lively:


Transitions

Animations control how a view changes. Transitions control how a view arrives on screen or leaves the screen.

You can use the .transition(.slide) or .transition(.opacity) modifiers in combination with withAnimation to create beautiful entrance effects!


Exercise

Which function block do you use to trigger an explicit animation when updating a state variable?