magnuskahr

writing code

Advantages of Using withAnimation

In my day-to-day use of SwiftUI, I prefer to write animations declaratively:

Color.red
    .opacity(dim ? 0.2 : 1)
    .animation(.easeOut, value: dim)

This approach is clean and keeps the animation scoped to the specific view it is applied to. However, there are scenarios where withAnimation becomes the better choice. Using withAnimation allows animations to affect elements outside the local scope, enabling more complex and visually balanced behavior.

Example: Expandable Views

Expandable views, which conditionally show their content, are common in SwiftUI. For instance, the built-in DisclosureGroup provides this behavior. However, if animations remain local to the view, subtle visual bugs may occur when these views are used within a ScrollView.

Consider the following implementation of an expandable view:

VStack {
    Button("Toggle content") {
        showContent.toggle()
    }
    if showContent {
        content
    }
}
.animation(.easeOut, value: showContent)

While the animation modifier ensures the VStack animates properly, placing this view in a ScrollView introduces an issue: other views below the expanding content will jump to their new positions instead of animating smoothly. This happens because the animation modifier only applies locally to the VStack.

The Solution: withAnimation

To fix this issue, you can replace the animation modifier with withAnimation. This approach ensures that all dependent views, whether directly or indirectly affected (e.g., by the resulting height change), animate smoothly:

VStack {
    Button("Toggle content") {
        withAnimation(.easeOut) {
            showContent.toggle()
        }
    }
    if showContent {
        content
    }
}

By using withAnimation, the animation is no longer confined to the VStack. Instead, it propagates to all layout changes, creating a seamless experience even in a ScrollView.


By understanding when to use withAnimation, you can ensure your SwiftUI animations remain visually cohesive and avoid common pitfalls. This approach is especially helpful when working with dynamic views and complex layouts.