如何在ContentView之外显示SwiftUI警报?

3
我正在建立一个Swift应用程序,并试图找出如何显示警报。我有一个独立的Swift文件进行一些计算,在某些条件下,我想向用户显示一个警报,告诉他们发生了错误。但是,我看到的大多数示例要求在ContentView中放置警报或以某种方式与视图连接,我无法弄清楚如何从任何视图外部的独立文件中显示警报。

我看到的大多数示例看起来像这样:

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

var body: some View {
    Button("Show Alert") {
        showingAlert = true
    }
    .alert("Important message", isPresented: $showingAlert) {
        Button("OK", role: .cancel) { }
    }
}}

.alert是一个视图修饰符。 根据文档:“...因为SwiftUI是一种声明性框架,所以您不会在想要呈现模态时立即调用方法。相反,您定义呈现的外观和SwiftUI应该呈现它的条件。然后,SwiftUI检测条件何时更改并为您进行呈现...”。因此,从View “外部”,只需更改条件即可呈现警报。 - workingdog support Ukraine
文档中说要始终将@State声明为私有的,那么我该如何从另一个类或文件中访问或设置它呢? - Charlie
使用ObservableObject视图模型代替State,并通过视图模型外部的属性管理警报。下一个链接应该很有帮助 https://stackoverflow.com/a/64596846/12299030。 - Asperi
1个回答

3
如果我正确理解了您的问题,您希望在计算中发生某些条件时在UI上显示一个警报。 计算过程发生在代码的其他地方,例如监视传感器的任务。
这里我提供一种方法,使用NotificationCenter,如示例代码所示。无论何时何地,在您的代码中发送NotificationCenter.default.post...,警报都会弹出。
class SomeClass {
    static let showAlertMsg = Notification.Name("ALERT_MSG")
    
    init() {
        doCalculations() // simulate showing the alert in 2 secs
    }
    
    func doCalculations() {
        //.... do calculations
        // then send a message to show the alert in the Views "listening" for it
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            NotificationCenter.default.post(name: SomeClass.showAlertMsg, object: nil)
        }
    }
}

struct ContentView: View {
    let calc = SomeClass() // for testing, does not have to be in this View
    @State private var showingAlert = false
    
    var body: some View {
        Text("calculating...")
            .alert("Important message", isPresented: $showingAlert) {
                Button("OK", role: .cancel) { }
            }
            // when receiving the msg from "outside"
            .onReceive(NotificationCenter.default.publisher(for: SomeClass.showAlertMsg)) { msg in
                self.showingAlert = true // simply change the state of the View
            }
    }
}

这几乎完全符合我的要求!但是,这是在使用RealityKit的AR应用中,警告框显示后,应用程序的相机视图会严重失真,即使解除警告框后仍然如此。您知道为什么会发生这种情况吗? - Charlie
1
很高兴它至少回答了你问题的一部分。不好意思,我在使用RealityKit开发AR应用方面没有经验。建议你发布你的问题代码并提出另一个问题。 - workingdog support Ukraine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接