Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Delayed Animation in SwiftUI
Written by Team Kodeco

Animations are a great way to add interactivity and beauty to your app. In SwiftUI, creating an animation is as simple as specifying the properties to animate and how long the animation should take using the withAnimation modifier. But what if you want to delay an animation? In this recipe, you’ll learn how to create a delayed animation in SwiftUI.

To add a delay to an animation, you can use the delay modifier along with the withAnimation modifier. The delay modifier specifies the amount of time the animation should wait before starting. Here’s an example:

struct ContentView: View {
  @State private var isAnimating = false

  var body: some View {
    VStack {
      Button("Animate") {
        withAnimation(.easeInOut(duration: 2).delay(1)) {
          isAnimating.toggle()
        }
      }
      .padding()
      RoundedRectangle(cornerRadius: isAnimating ? 50 : 10)
        .foregroundColor(.blue)
        .frame(width: isAnimating ? 300 : 100, height: isAnimating ? 300 : 100)
        .animation(.easeInOut(duration: 2), value: isAnimating)
    }
  }
}

Your preview should look like this:

Use the delay parameter to prevent an animation from starting immediately.
Use the delay parameter to prevent an animation from starting immediately.

In the example above, you have a Button that toggles the value of isAnimating. When isAnimating is true, the rounded rectangle’s width and height increase while its corner radius decreases. You can see that this change is animated using the .animation modifier.

But, you also specified a delay of 1 second using the .delay(1) modifier in the withAnimation closure.

The result is that when you tap the Animate button, the rectangle waits for 1 second before the animation starts. This creates a nice effect where the button and rectangle do not animate at the same time.

In conclusion, using the delay and withAnimation modifiers, you can easily add a delay to animations in SwiftUI. Now go ahead and add some life to your app with delayed animations!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.