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
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing 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
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftdata

swiftui

swift

ios

How to store images in SwiftData

Learn how to efficiently store larger amounts of data in SwiftData.

27 Nov 2023 · 1 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum