Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Repeating Animation in SwiftUI
Written by Team Kodeco

Have you ever wanted to make an animation loop continuously? SwiftUI has a built-in way to create a repeating animation that automatically restarts after its duration has completed. In this cookbook entry, you’ll learn how to make a repeating animation in SwiftUI.

To create a repeating animation, you can use the repeatForever method on an animation object. Let’s see how it works in practice:

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

  var body: some View {
    Circle()
      .fill(.blue)
      .frame(width: 50, height: 50)
      .scaleEffect(isAnimating ? 1.5 : 1)
      .animation(
        isAnimating ?
          .easeInOut(duration: 1).repeatForever(autoreverses: true) :
          .default,
        value: isAnimating
      )
      .onAppear {
        isAnimating = true
      }
  }
}

Your preview should look like this:

Use repeatForever to make an animation loop continuously.
Use repeatForever to make an animation loop continuously.

In this example, you have a blue circle that scales up and down continuously. You use the repeatForever method to make the animation repeat indefinitely. By setting autoreverses to true, the animation will also reverse itself after each cycle, giving a smooth bouncing effect.

To start the animation, you use the onAppear modifier to set the initial state of isAnimating to true. This will trigger the animation to start when the view appears.

And that’s it! With just a few lines of code, you can create a repeating animation that adds some extra flair to your user interface.

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.