認識 SwiftUI 的 Alert

你還愛我嗎 ? 會不會像周蕙唱的,愛不愛結果都教人傷心呢 ? 接下來就讓我們用 SwiftUI 的 Alert 顯示愛不愛吧 。

目標: 點選按鈕顯示愛或不愛的 alert,我們用兔子當例子,就算牠不愛我們,我們也不會太難過。

綁定型別 Bool 變數的 alert function

透過 function alert 顯示 alert。function alert 接受型別 Binding<Bool> 的參數,所以我們必須傳入型別 Bool 的變數讓它綁定。當變數內容為 true 時,alert 將顯示,當內容為 false 時,alert 將害羞地藏起來。

你還愛我嗎的 Alert 範例

struct ContentView: View {
@State private var showAlert = false
@State private var alertTitle = ""

var body: some View {
Button {
showAlert = true
alertTitle = ["愛", "不愛"].randomElement()!
} label: {
VStack {
Image(.rabbit)
.resizable()
.scaledToFit()
Text("你還愛我嗎")
}
}
.alert(alertTitle, isPresented: $showAlert) {
Button("OK") {

}
}
}
}

說明。

.alert(alertTitle, isPresented: $showAlert) {
Button("OK") {

}
}

透過 View 的 function alert(_:isPresented:actions:) 顯示 Alert。

func alert<S, A>(
_ title: S,
isPresented: Binding<Bool>,
@ViewBuilder actions: () -> A
) -> some View where S : StringProtocol, A : View

參數說明。

  • title

alert 顯示的標題。

  • isPresented

決定是否顯示 Alert,當 isPresented 為 true 時顯示 alert。為了傳入 Binding<Bool> 型別的資料,我們事先以 @State 宣告 Bool 型別的 showAlert,然後以 $showAlert 傳入。

  • actions

設定 alert 顯示的 button,在此我們產生 button OK。button 點選後將關掉 alert,我們也可在 button 的 closure 裡設定點選後額外要做的事。

Button {
showAlert = true
alertTitle = ["愛", "不愛"].randomElement()!
} label: {
VStack {
Image(.rabbit)
.resizable()
.scaledToFit()
Text("你還愛我嗎")
}
}

點選 button 時將 showAlert 設為 true,alertTitle 設為愛或不愛,showAlert 為 true 時將觸發 alert 顯示,alertTitle 是 alert 顯示的標題。

結果。

如下圖所示,點選 button 將顯示 alert。當我們點選 OK 關掉 alert 時,showAlert 將自動被設為 false。

預設的 ok button

參數 actions 沒有產生任何 button 時,會顯示預設的 ok button。

.alert(alertTitle, isPresented: $showAlert) {
}

顯示 message (副標題)

透過參數 message 設定副標題。

.alert(alertTitle, isPresented: $showAlert) {

} message: {
Text("真心不騙")
}

Alert 的 button 樣式

產生 alert 時,我們還可在產生 button 時傳入參數 role 設定 button 的樣式。

.alert(alertTitle, isPresented: $showAlert) {
Button("OK") { }
Button("Cancel", role: .cancel) { }
Button("Destructive", role: .destructive) { }
}, message: {
Text("真心不騙")
}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com