在給用戶提供反饋的同時,有時也可以用來協助調試應用程序,最常見的方式之一就是使用警告訊息。
SwiftUI 提供了 .alert() 修飾符,我們可以根據某些條件來顯示警告。
讓我們從以下範例開始,其中有一個帶有計數器的 Button:
import SwiftUI
struct ContentView: View {
@State var count = 0
var body: some View {
Button("Count: \(count)") {
self.count += 1
}
.font(.title)
}
}
當 count 達到 10 時,我希望顯示一個警告訊息。
我們該如何做到這一點?
我可以在 ContentView 中添加一個名為 showAlert 的布爾屬性,並編輯 Button 的點按操作內容:
struct ContentView: View {
@State var count = 0
@State var showAlert = false
var body: some View {
Button("Count: \(count)") {
self.count += 1
if self.count == 10 {
showAlert = true
self.count = 0
}
}
.font(.title)
}
}
當我們達到 10,我們將 showAlert 設置為 true,並將計數重置為 0。
然後,我們將 .alert() 修飾符添加到 Button 視圖:
.alert(isPresented: $showAlert) {
Alert(title: Text("Great!"), message: Text("You reached 10"))
}
此警告僅在 showAlert 屬性為 true 時顯示。當我們關閉警告訊息時,showAlert 屬性會自動設置為 false。
以下是完整的程式碼:
struct ContentView: View {
@State var count = 0
@State var showAlert = false
var body: some View {
Button("Count: \(count)") {
self.count += 1
if self.count == 10 {
showAlert = true
self.count = 0
}
}
.font(.title)
.alert(isPresented: $showAlert) {
Alert(title: Text("Great!"), message: Text("You reached 10"))
}
}
}
嘗試運行應用程序。計數器從 0 開始。點擊按鈕,計數器將增加:
直到達到 10:
然後,計數器將重新從 0 開始: