How do I write a animation in SwiftUI

Asked on 05/15/2025

1 search

To write an animation in SwiftUI, you can use the SwiftUI animation APIs to create smooth and interactive animations. Here's a basic example of how you can animate a view in SwiftUI:

  1. Basic Animation: You can wrap your state changes with the withAnimation function to animate the changes. For example, if you want to animate a change in a view's position or opacity, you can do it like this:

    struct ContentView: View {
        @State private var isVisible = false
    
        var body: some View {
            VStack {
                Button("Toggle") {
                    withAnimation {
                        isVisible.toggle()
                    }
                }
    
                if isVisible {
                    Text("Hello, SwiftUI!")
                        .transition(.slide)
                }
            }
        }
    }
    
  2. Custom Animations: You can also create custom animations using the Animation struct. For example, you can define a spring animation:

    struct ContentView: View {
        @State private var scale: CGFloat = 1.0
    
        var body: some View {
            VStack {
                Button("Animate") {
                    withAnimation(.spring(response: 0.5, dampingFraction: 0.3, blendDuration: 0)) {
                        scale = scale == 1.0 ? 1.5 : 1.0
                    }
                }
    
                Circle()
                    .frame(width: 100, height: 100)
                    .scaleEffect(scale)
            }
        }
    }
    
  3. Advanced Techniques: For more advanced animations, you can use SwiftUI's animatableData to create custom animations, or use shaders for complex visual effects. For example, in the session Create custom visual effects with SwiftUI, a ripple effect is created using shaders and a view modifier to animate based on external changes like gestures.

For a deeper dive into SwiftUI animations, you can refer to the session Enhance your UI animations and transitions, which covers various animation techniques and how to apply them in SwiftUI.