Logo for tanaschita.com

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:

  1. animation(_:value:) view modifier for animations when a certain state value changes
  2. 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.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

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.brown
var 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.brown
var 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.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

animations

swift

ios

How to delay an animation in SwiftUI

Learn how to wait for a certain amount of time before starting a SwiftUI animation.

26 Feb 2024 · 2 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum