Home > Net >  Alert ProgressView (Activity Indicator) in SwiftUI
Alert ProgressView (Activity Indicator) in SwiftUI

Time:09-11

Is there any way to add Activity View (Indicator) into SwiftUI Alert somewhere? I'm just curious because I haven't found any appropriate answer on such question. I need something like this: enter image description here

I'm using iOS 14 SwiftUI Alert with optional state that conforms to Identifiable. There was a way in UIKit UIAlertController to add subview to the alert's view. Is there some ideas on that, thanks in advance.

CodePudding user response:

For maximum control over the content and behaviour of the alert popup, I recommend just creating your own

struct ContentView: View {
    var alertShown: Bool = false
    var body: some View {
        ZStack {
            VStack {
                // your main view
            }
            .blur(radius: alertShown ? 15 : 0)
            if alertShown {
                AlertView()
            }
        }
    }
}

struct AlertView: View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 6)
                .foregroundColor(.blue)
            VStack {
                HStack {
                    ProgressView()
                    Text("Processing...")
                }
                Button(action: {
                    // action
                }, label: {
                    Text("Cancel")
                })
                .foregroundColor(.black)
            }
        }
    }
}

CodePudding user response:

I had to something similar in an app and basically it is not possible using the native SwiftUI .alert API. You can

  • Use a custom UIAlertController
  • Make a custom overlay that does what you want

Because of that I created CustomAlert so I can easily make alerts with custom content. It essentially recreates the alert in SwiftUI and exposes a similar API for it.

.customAlert(isPresented: $alertShown) {
    HStack(spacing: 16) {
        ProgressView()
            .progressViewStyle(.circular)
            .tint(.blue)
        Text("Processing...")
            .font(.headline)
    }
} actions: {
    Button(role: .cancel) {
        // Cancel Action
    } label: {
        Text("Cancel")
    }
}
  • Related