我正在構建一個 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) { }
}
}}
uj5u.com熱心網友回復:
如果我正確理解您的問題,您希望alert在計算中發生某些情況時在 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
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450996.html
