如何在所有其他视图和工作表之上显示 SwiftUI Alert (MacOS)

Fre*_*zek 5 alert global popup swiftui

我试图Alert在当时打开的所有其他视图、工作表或警报之上全局显示一个全局相关错误,这样我就可以显示程序运行时随时可能发生的全局相关错误。这可能吗?我的程序适用于 Mac,因此 UIKit 解决方法不起作用...提前致谢:)

您可以在任何视图上应用以下修改器,它将在该视图以及在此视图中创建的其他工作表和警报之上显示错误,但不会在子视图中创建的那些工作表之上显示错误。

MyView()
    .modifier(AlertPresenter())

struct AlertPresenter: ViewModifier {
    @StateObject var alertViewModel: AlertViewModel = AlertViewModel()

    func body(content: Content) -> some View {
        content
            .alert(alertViewModel.errorTitle,
                   isPresented: $alertViewModel.showError,
                   actions: {
            Button("Ok") {
                alertViewModel.showError = false
            }
        }, message: {
            Text(alertViewModel.errorMessage)
        })
    }
}

class AlertViewModel: ObservableObject {    
    @Published var showError: Bool = false
    @Published var errorTitle: String = "An Error Occurred!"
    @Published var errorMessage: String = unknownString
    
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(errorOccurred), name: errorOccurredNotificationName, object: nil)
    }
    
    @objc func errorOccurred(_ notification: Notification) {
        guard let error = notification.object as? Error else { return }
        errorMessage = error.localizedDescription
        showError = true
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

而不是使用修饰符。也许你可以这样做:

extension View {
    @ViewBuilder func errorAlert(error: Binding<Error?>, buttonTitle: LocalizedStringKey = "xloc.generic.ok", action: (() -> Void)? = nil) -> some View {
        let localizedAlertError = LocalizedAlertError(error: error.wrappedValue)
        alert(isPresented: .constant(localizedAlertError != nil), error: localizedAlertError) { _ in
            Button(buttonTitle) {
                action?()
                error.wrappedValue = nil
            }
        } message: { error in
            Text(error.failureReason ?? error.recoverySuggestion ?? "")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您将能够像调用 .alert() 一样显示错误警报。这是你想做的事吗?