Swift UIAlertController使用⚠️ – 警告對話框教學

在開發 iOS App 時,有時候會需要在 App 中加入一些警告對話框,來提醒使用者做出一些決定,或是提醒使用者一些重要的訊息,在 Swift 中,可以使用 UIAlertController 來建立警告對話框,下面就來看看如何使用 UIAlertController 來建立警告對話框吧!

建立 UIAlertController

要建立一個 UIAlertController,可以使用以下的程式碼:

let alertController = UIAlertController(title: "警告", message: "這是一個警告對話框", preferredStyle: .alert)

上面的程式碼會建立一個 UIAlertController,並且設定 title 為「警告」,message 為「這是一個警告對話框」,preferredStyle 為 .alert,這樣就會建立出一個警告對話框。

加入按鈕

在 UIAlertController 中,可以加入多個按鈕,來讓使用者做出決定,可以使用以下的程式碼來加入按鈕:

let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)

上面的程式碼會建立一個 UIAlertAction,並且設定 title 為「OK」,style 為 .default,handler 為 nil,然後將這個 UIAlertAction 加入到 UIAlertController 中,這樣就會在警告對話框中加入一個「OK」按鈕。

顯示 UIAlertController

當 UIAlertController 建立完成後,可以使用以下的程式碼來顯示警告對話框:

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

上面的程式碼會將 UIAlertController 顯示出來,讓使用者可以看到警告對話框,並且做出決定。

總結

在 Swift 中,可以使用 UIAlertController 來建立警告對話框,並且加入按鈕,讓使用者做出決定,最後再將 UIAlertController 顯示出來,讓使用者可以看到警告對話框,並且做出決定。

推薦閱讀文章

推薦閱讀文章

            <a href="https://medium.com/@jimmy.yoon/swift-uialertcontroller-%E4%BD%BF%E7%94%A8-%E8%AD%A6%E5%91%8A%E5%B0%8D%E8%A9%B1%E6%A1%86%E6%95%99%E5%AD%B8-f9d9f3f3f3f3">Swift UIAlertController使用⚠️ - 警告對話框教學</a><br>
            <a href="https://www.appcoda.com.tw/uialertcontroller/">iOS 警告對話框(UIAlertController)教學</a><br>
            <a href="https://www.jianshu.com/p/e9a9f9a7f9f3">Swift UIAlertController使用 - 警告對話框教學</a><br>
            <a href="https://www.ioscreator.com/tutorials/uialertcontroller-ios-tutorial">UIAlertController Tutorial: Getting Started</a><br>
            <a href="https://www.hackingwithswift.com/example-code/uikit/how-to-use-uialertcontroller">How to use UIAlertController</a

延伸閱讀本站文章

更多swift相關文章

Swift UIAlertController使用⚠️ - 警告對話框教學

Categorized in:

Tagged in:

,