Understanding basic animations in SwiftUI
Learn different options to animate SwiftUI views.
16 Jan 2023 · 4 min read
To add an animation to a SwiftUI view, the framework provides the following two options:
- animation(_:value:) view modifier for animations when a certain state value changes
- withAnimation(_:_:) global function which we can use to apply state changes and create animations for all affected views
To understand each option, let's look at a simple example where each time we tap on a button, its background color changes.

Adding animations with animation(_:value:)
The animation(_:value:) view modifier is useful when we need to animate a view every time a specific value changes. We can use it as follows:
@State private var color = Color.brownvar body: some View {Button("Change color") {color = color == .brown ? .mint : .brown}.padding(20).background(color).foregroundColor(.white).animation(.easeInOut, value: color)}
To change the button's color with animation, we pass the color variable as value parameter which then applies the animation every time the value of the color variable changes.
Adding animations with the withAnimation(_:_:) global function
By using the withAnimation(_:_:) global function, the same example can be achieved as follows:
@State private var color = Color.brownvar body: some View {Button("Change color") {withAnimation(.easeInOut) {color = color == .brown ? .mint : .brown}}.padding(20).background(color).foregroundColor(.white)}
In the solution above, we call the withAnimation(_:_:) global function every time the button is tapped and pass all state changes to the body parameter of the function.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips