SwiftUI Alert 警告與對話框教學

Alert 是用來顯示重要訊息或要求使用者確認的彈出框(例如「確定要刪除嗎?」)。它通常包含一個標題、訊息內容以及一個或多個按鈕。

基礎 Alert

使用 .alert 修飾符並綁定一個布林值狀態來控制顯示。

struct ContentView: View {
    @State private var showAlert = false
    
    var body: some View {
        Button("顯示警告") {
            showAlert = true
        }
        .alert("發生錯誤", isPresented: $showAlert) {
            Button("確定", role: .cancel) { }
        } message: {
            Text("網路連線失敗,請稍後再試。")
        }
    }
}
  • actions 閉包:定義按鈕。如果不提供,系統預設會給一個 "OK" 按鈕。
  • message 閉包:定義詳細訊息(可選)。

處理多個按鈕

你可以加入多個按鈕,例如「刪除」與「取消」。記得善用 role 來標示按鈕性質。

.alert("確定刪除?", isPresented: $showDeleteAlert) {
    Button("刪除", role: .destructive) {
        // deleteAction()
    }
    Button("取消", role: .cancel) { }
} message: {
    Text("此動作無法復原。")
}

ConfirmationDialog (ActionSheet)

如果你需要提供多個選項讓使用者選擇(通常從底部滑出),請使用 confirmationDialog(在 iOS 15 以前稱為 ActionSheet)。

.confirmationDialog("選擇大頭貼", isPresented: $showDialog) {
    Button("從相簿選擇") { }
    Button("拍照") { }
    Button("取消", role: .cancel) { }
}