Swift 警告控制項 (UIAlertController) 完整學習指南 – 2025 最新語法與最佳實踐

Swift 是一種現代化的程式語言,讓開發者能夠快速且高效地開發 iOS 應用程式。其中,UIAlertController 是一個強大的警告控制項,能讓開發者輕鬆建立警告視窗,供使用者做出決策。在這篇文章中,我們將深入介紹如何使用 UIAlertController,包含最新的語法、最佳實踐及各種實作範例。

建立 UIAlertController

要建立一個 UIAlertController,你需要使用 UIAlertController 類別的 init(title:message:preferredStyle:) 方法,它會回傳一個 UIAlertController 物件。

let alertController = UIAlertController(title: "標題", message: "這是一個訊息", preferredStyle: .alert)

在上面的程式碼中,我們建立了一個 UIAlertController 物件,並指定了標題、訊息和樣式(警告視窗)。

添加按鈕

建立 UIAlertController 物件後,我們可以使用 addAction(_:) 方法來添加按鈕。

let okAction = UIAlertAction(title: "確定", style: .default) { action in
    print("使用者按下確定")
}
alertController.addAction(okAction)

在上面的程式碼中,我們建立了一個 UIAlertAction 物件,指定標題、樣式及處理器,然後將其添加到 UIAlertController 中。

顯示 UIAlertController

當建立並添加按鈕後,可以使用 present(_:animated:completion:) 方法來顯示警告控制項。

self.present(alertController, animated: true, completion: nil)

在這段程式碼中,我們使用 present(_:animated:completion:) 方法將 UIAlertController 顯示出來。

錯誤排除

在使用 UIAlertController 時,可能會遇到一些常見錯誤:

  • 未正確設置視圖控制器: 確保在有效的視圖控制器中調用 present(_:animated:completion:) 方法。
  • 按鈕處理器未被調用: 確保按鈕的處理器已正確設置,並且在按鈕被按下後能夠正常執行。

延伸應用

你可以使用 UIAlertController 的其他樣式來實現不同的功能,例如使用 .actionSheet 來顯示動作清單。在需要用戶做出選擇時,這是一個非常有用的功能。

let actionSheetController = UIAlertController(title: "選擇一個選項", message: "請選擇", preferredStyle: .actionSheet)

在這個範例中,我們創建了一個動作清單,讓使用者選擇。

總結

在本文中,我們介紹了如何使用 Swift 的 UIAlertController 來建立和顯示警告視窗,並且展示了添加按鈕及顯示的方法。這些基本操作能幫助你快速上手並在實際開發中靈活應用。

如需更深入了解 UIAlertController,請參考 Apple 的官方文檔,獲取更多資訊和最佳實踐。

Q&A(常見問題解答)

1. UIAlertController 可以顯示多少個按鈕?

UIAlertController 可以顯示多個按鈕,使用 addAction(_:) 方法即可添加更多按鈕。

2. 如何在 UIAlertController 中添加文本輸入框?

你可以使用 addTextField(configurationHandler:) 方法來添加文本輸入框,並自定義其屬性。

3. UIAlertController 與其他警告視圖的區別是什麼?

UIAlertController 提供了一個統一的 API 來處理警告視窗和動作清單,相較於之前的 UIAlertView 和 UIActionSheet,使用更為簡便。

Swift 警告控制項(UIAlertController) 🚨學習教學 – 瞬間學会

Categorized in:

Tagged in:

,