Animations,Swift UI How to Create a Loading Animation in SwiftUI

How to Create a Loading Animation in SwiftUI

SwiftUI, Apple’s innovative UI toolkit, has made designing user interfaces a breeze for developers. One of the common UI elements in applications is a loading animation. It provides feedback to users, indicating that a process or task is ongoing. In this blog post, we’ll guide you through creating a simple yet effective loading animation in SwiftUI.

Why Use Loading Animations?

Before diving into the code, it’s essential to understand the significance of loading animations:

  1. User Feedback: Loading animations inform users that the app is processing something, preventing confusion or the misconception that the app has frozen.
  2. Enhanced User Experience: A smooth and engaging animation can enhance the user experience, making the wait less tedious.
  3. Aesthetic Appeal: A well-designed animation can add to the overall aesthetics of your app.

Creating a Loading Animation in SwiftUI

Here’s a step-by-step guide to creating a loading animation using SwiftUI:

struct LoadingAnimation: View {
    @State private var isLoading = false

    var body: some View {
        HStack {
            ForEach(0...4, id: \.self) { index in
                    .frame(width: 10, height: 10)
                    .scaleEffect(self.isLoading ? 0 : 1)
                    .animation(.linear(duration: 0.6)
                                .delay(0.2 * Double(index)), value: isLoading)
        .onAppear() {
            self.isLoading = true

Breaking Down the Code:

  1. State Variable: We declare a state variable isLoading to keep track of the animation’s status.
  2. HStack: This stacks our animation dots horizontally.
  3. ForEach Loop: We use a loop to create five circles (dots) for our animation.
  4. Circle: Represents each dot of the animation.
  5. .frame(): Sets the size of each dot.
  6. .foregroundStyle(): Colors the dot green.
  7. .scaleEffect(): This is where the magic happens. We use the scaleEffect modifier to grow or shrink the dot based on the isLoading state.
  8. .animation(): Defines the animation properties. We use a linear animation with a duration of 0.6 seconds. The animation repeats indefinitely. The delay ensures that each dot starts its animation slightly after the previous one, creating a wave effect.
  9. .onAppear(): As soon as the view appears, we set isLoading to true, triggering the animation.


SwiftUI offers a plethora of tools and modifiers to create engaging animations with minimal code. The above loading animation is just a starting point. Feel free to experiment with different shapes, colors, and animation effects to make it uniquely yours. Remember, a good loading animation can significantly enhance your app’s user experience, so invest some time in getting it right!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post