withAnimation
withAnimation wraps state changes to produce smooth transitions. It's one of the most common ways to add animation to a SwiftUI view.
Use Case
A common use case for withAnimation is when you want to animate the appearance or disappearance of a view based on a state change. For example, you might want to animate a button that toggles the visibility of a text label.
import SwiftUI
struct ContentView: View {
@State private var isVisible = false
var body: some View {
VStack {
Button("Toggle Text") {
withAnimation {
isVisible.toggle()
}
}
if isVisible {
Text("Hello, SwiftUI!")
.transition(.slide)
}
}
}
}
In this example, when the button is pressed, the isVisible state toggles within a withAnimation block, causing the text to slide in and out smoothly.
Caveats
While withAnimation is powerful, there are a few caveats to keep in mind:
-
Performance: Overusing animations can lead to performance issues, especially on older devices. Use animations judiciously to ensure a smooth user experience.
-
State Changes: Ensure that the state changes you want to animate are directly related to the views being animated. If the state change does not affect the view hierarchy, the animation may not work as expected.
-
Animation Types: Not all view changes can be animated. Some properties may not support animation, so be sure to test your animations thoroughly.
Accessibility
When using animations, it's important to consider accessibility. Some users may have motion sensitivity and prefer reduced motion settings. SwiftUI respects the user's system preferences for reduced motion, so animations will be disabled if the user has enabled this setting in their device's accessibility options.
See Respecting Reduced Motion for more information.
Wrap up
withAnimation is the simplest way to add animation to a SwiftUI app. Keep reduced motion in mind — check out the Reduced Motion post for how to handle that properly.
Resources:
Read more
- Interpolation and formatting in Text • 4 minutes reading time.
- Variadic Parameters • 3 minutes reading time.
- iCloud Drive Tips & Tricks • 8 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook