Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Spinning Activity Indicator in SwiftUI
Written by Team Kodeco

Activity indicators, sometimes known as loading spinners, are prevalent user interface elements used to denote that the content is loading. You’ll often see messages like “Please wait” or “Loading…” accompanying these spinners. SwiftUI allows for the easy creation of custom spinners using the built-in ProgressView.

Here’s how you can create a continuous, indeterminate spinner, which spins until the content is ready, with SwiftUI’s ProgressView.

struct SpinnerView: View {
  var body: some View {
    ProgressView()
      .progressViewStyle(CircularProgressViewStyle(tint: .blue))
      .scaleEffect(2.0, anchor: .center) // Makes the spinner larger
      .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
          // Simulates a delay in content loading
          // Perform transition to the next view here
        }
      }
  }
}

struct ContentView: View {
  var body: some View {
    SpinnerView()
  }
}

Your preview should look like this:

Use ProgressView with a CircularProgressViewStyle to create a loading spinner.
Use ProgressView with a CircularProgressViewStyle to create a loading spinner.

In the example above, SpinnerView contains a circular spinner that spins indefinitely until the content is ready. You modify the color of the spinner by creating a CircularProgressViewStyle and setting its tint property to the desired color, in this case, blue. The spinner size is increased using the scaleEffect modifier.

Upon the initial appearance of the view, you simulate a content loading delay using DispatchQueue.main.asyncAfter, which introduces a pause of 2 seconds. Once the loading completes, you transition to the next view.

The creation of activity indicators is a vital step in delivering a smooth user experience. It signals to the user that the app is actively processing or loading content. With SwiftUI, creating a customized activity indicator is achievable with just a few lines of code.

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.