Creating a Loading Indicator in SwiftUI: A Step-by-Step Guide

Creating a Loading Indicator in SwiftUI

When building a mobile application, it is common to include a loading indicator to provide feedback to the user during long-running tasks or when waiting for data to load. In this article, we will explore how to create a loading indicator in SwiftUI.

Understanding SwiftUI

SwiftUI is a modern framework provided by Apple for building user interfaces across all Apple platforms. It offers a declarative syntax that allows developers to describe the desired user interface and behavior of their app. With SwiftUI, developers can build UIs using a combination of views, modifiers, and layouts.

Designing the Loading Indicator

To design our loading indicator, we will start by creating a custom SwiftUI view that represents the loading state. This view will contain an activity indicator, and optionally, a text label to display a message to the user.

import SwiftUI

struct LoadingIndicator: View {
    var message: String?

    var body: some View {
        VStack {
            ProgressView() // Activity indicator

            if let message = message {
                Text(message)
                    .font(.headline)
                    .padding(.top, 10) // Add some padding below the activity indicator
            }
        }
        .padding() // Add padding around the entire loading indicator
        .background(Color.white) // Set background color to white
        .cornerRadius(10) // Add rounded corners to the loading indicator
        .shadow(radius: 5) // Add a subtle shadow for depth
    }
}

In the code above, we define the `LoadingIndicator` struct which conforms to the `View` protocol, making it a valid SwiftUI view. Inside the `body` property, we use a `VStack` to vertically stack the activity indicator and the optional message text. We then apply some styling to the view using modifiers, such as padding, background color, corner radius, and shadow.

Using the Loading Indicator

Now that we have our loading indicator defined, let’s see how we can use it in our SwiftUI views. We will demonstrate two use cases:

1. Basic Usage

The simplest usage of our loading indicator involves creating an instance of the `LoadingIndicator` view and displaying it conditionally based on a boolean flag that represents the loading state.

import SwiftUI

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

    var body: some View {
        VStack {
            Button("Fetch Data") {
                isLoading = true

                // Perform the loading task
                fetchData { [weak self] in
                    DispatchQueue.main.async {
                        self?.isLoading = false
                    }
                }
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
            
            if isLoading {
                LoadingIndicator()
                    .frame(width: 100, height: 100)
            }
        }
    }

    func fetchData(completion: @escaping () -> Void) {
        // Simulate a network request
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            completion()
        }
    }
}

In the code above, we use the `@State` property wrapper to create a boolean flag `isLoading`. When the user taps the „Fetch Data“ button, we set `isLoading` to true and initiate the loading task. Once the task is completed, we set `isLoading` back to false, which in turn hides the loading indicator.

Inside the `body` property of the `ContentView` view, we conditionally display the `LoadingIndicator` view if `isLoading` is true. We also apply some styling to the button to make it prominent (padding, background color, text color, and corner radius).

2. Custom Message

It is also possible to display a custom message alongside the loading indicator by passing a string to the `message` parameter of the `LoadingIndicator` view.

import SwiftUI

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

    var body: some View {
        VStack {
            Button("Fetch Data") {
                isLoading = true

                // Perform the loading task
                fetchData { [weak self] in
                    DispatchQueue.main.async {
                        self?.isLoading = false
                    }
                }
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)

            if isLoading {
                LoadingIndicator(message: "Loading data...")
                    .frame(width: 200, height: 200)
            }
        }
    }

    func fetchData(completion: @escaping () -> Void) {
        // Simulate a network request
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            completion()
        }
    }
}

In the updated code above, we pass the message string „Loading data…“ to the `LoadingIndicator` view. The message is then displayed below the activity indicator, as specified in the custom view’s layout.

Closing Summary

In this article, we learned how to create a loading indicator in SwiftUI. We designed a custom view called `LoadingIndicator`, which includes an activity indicator and an optional message label. We then explored two usage scenarios, including basic usage and displaying a custom message. By leveraging the power of SwiftUI, we can easily add loading indicators to our apps, providing a better user experience and feedback during long-running tasks.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Chat Icon

Diese Seite verwendet Cookies, um die Nutzerfreundlichkeit zu verbessern. Mit der weiteren Verwendung stimmst du dem zu.

Datenschutzerklärung