Let’s dive into adding basic animations to your SwiftUI views using scaling, rotation, fading, and the withAnimation function.

struct ContentView: View {
    @State private var isScaled = false

    var body: some View {
        Button("Scale Me!") {
            withAnimation(.easeInOut(duration: 1)) {
                isScaled.toggle()
            }
        }
        .scaleEffect(isScaled ? 1.5 : 1)
    }
}

In this example, the scaleEffect modifier changes the size of the button. When the button is tapped, withAnimation wraps the state change (isScaled.toggle()), triggering the animation over 1 second using an ease-in-out curve.

struct ContentView: View {
    @State private var rotationAngle: Double = 0

    var body: some View {
        Button("Rotate Me!") {
            withAnimation(.linear(duration: 2)) {
                rotationAngle += 360 // Full rotation
            }
        }
        .rotationEffect(.degrees(rotationAngle))
    }
}

Here, rotationEffect applies a rotation to the button. Clicking the button increases the rotationAngle by 360 degrees, causing a full rotation over 2 seconds with a linear animation.

3. Fading (Opacity):

struct ContentView: View {
    @State private var isVisible = true

    var body: some View {
        Button("Toggle Visibility") {
            withAnimation {
                isVisible.toggle()
            }
        }
        .opacity(isVisible ? 1 : 0)
    }
}

The opacity modifier controls the visibility of the button. The withAnimation block ensures that the change in isVisible is animated, making the button fade in and out smoothly.

Combining Animations:

You can chain multiple animation modifiers to create more complex effects:

Button("Animate!") {
    withAnimation(.spring()) { // Use a spring animation
        isScaled.toggle()
        rotationAngle += 180
        isVisible.toggle()
    }
}
.scaleEffect(isScaled ? 1.5 : 1)
.rotationEffect(.degrees(rotationAngle))
.opacity(isVisible ? 1 : 0)

Key Points About withAnimation:

  • Implicit vs. Explicit: By default, SwiftUI applies implicit animations to state changes within a view’s body. withAnimation gives you more explicit control over when and how animations occur.
  • Grouping: Any state changes made within the withAnimation block will be animated together as a single, coordinated animation.
  • Customization: You can customize animation types (e.g., .linear.easeInOut.spring), durations, and other parameters.