Logo for tanaschita.com

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

When working with animations in SwiftUI, we sometimes need to delay an animation, for example when showing a UI element to users and then hiding it after a certain amount of time.

Let's jump right in and see how to do that.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
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

Let's look at the following example:

@State private var offset = -60.0 // 1.
var body: some View {
ErrorView()
.offset(y: offset)
.onAppear {
// 2.
withAnimation(.bouncy) {
offset = 60.0
} completion: {
// 3.
withAnimation(.bouncy) {
offset = -60.0
}
}
}
}

What we do in the code above is:

  1. Setting the initial offset of the view out of screen bounds so it's not visible at first.
  2. As soon as the view appears, we animate it to a different offset so it becomes visible on the screen.
  3. As soon as the animation is completed, we animate the view back to a non-visible offset.

What is missing in the example is a delay, so the view stays on the screen for a few seconds before bouncing back.

Since delays are built-in into SwiftUI animations, we can achieve this with one simple call. All we need to do is to add a delay to our second animation:

withAnimation(.bouncy.delay(3))
Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
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

Understanding basic animations in SwiftUI

Learn different options to animate SwiftUI views.

16 Jan 2023 · 4 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum