ProgressView in SwiftUI 2.0 (How to display the ProgressView during an operation)

3.3k Views Asked by At

I'm trying to show a ProgressView while something is being processed, and the app busy.

in this exemple during the for

import SwiftUI

struct ContentView: View {

@State var isLoading:Bool = false

var body: some View {
    ZStack{

            if self.isLoading {
                ProgressView()
                    .zIndex(1)
            }

        Button("New View"){
      
            self.isLoading = true
           
            var x = 0
            for a in 0...5000000{
                x += a
            }
            
            self.isLoading = false
      
            print("The End: \(x)")
        }
        .zIndex(0)
    }
}
}  

In my app the ProgressView don't appears when i Press the button

So how I can display the ProgressView while the for is running?

I'm using Xcode 12

1

There are 1 best solutions below

1
On

You just blocked UI thread with sync long button action. The solution is to make it in background.

Here is possible fix (tested with Xcode 12 / iOS 14):

struct ContentView: View {

    @State var isLoading:Bool = false

    var body: some View {
        ZStack{

            if self.isLoading {
                ProgressView()
                    .zIndex(1)
            }

            Button("New View"){
                self.isLoading = true

                DispatchQueue.global(qos: .background).async {
                    var x = 0
                    for a in 0...500000 {
                        x += a
                    }

                    DispatchQueue.main.async {
                        self.isLoading = false
                        print("The End: \(x)")
                    }
                }
            }
            .zIndex(0)
        }
    }
}