UIAlertController 警告訊息與選單

Anny
6 min readOct 5, 2020

--

我們平時使用App的警告訊息視窗通常為兩種。

一種是從中間彈出(右圖),另一種是由下彈出(左圖)。

以下就來介紹如何呈現這兩種警告訊息,使用UIAlertController 來實現。

將會提到包含:

  • alert & actionSheet 兩種方式
  • 按下按鈕選單執行不同動作
  • 增添文字輸入框

alert (右圖)

中間彈出的警告視窗用.alert

Step1:做出警告視窗 使用UIAlertController — preferredStyle 傳入 .alert

Step2:做按鈕 使用UIAlertAction

  • title — 按鈕名稱
  • style — 按鈕形式,有三種.default、.cancel、.destructive
  1. default — 預設樣式。
  2. cancel — 取消樣式,只能用一個,且會列在最下面。
  3. destructive — 警示樣式,使用在改變或刪除某些資料。(為紅色粗體)
  • handler—按下按鈕要執行的程式,沒有要執行的話填入nil

Step3:將按鈕加入警告視窗 — addAction 並顯示 — present

// Step1:做出警告視窗
let
controller = UIAlertController(title: "要允許此App取用您的位置嗎?", message: "此App需開啟定位服務", preferredStyle: .alert)
// Step2:做按鈕
let
allowAction = UIAlertAction(title: "使用App期間允許", style: .default, handler: nil)
// Step3:將按鈕加入警告視窗
controller.addAction(allowAction)
let allowOnceAction = UIAlertAction(title: "允許一次", style: .default, handler: nil)
controller.addAction(allowOnceAction)
let allowNotAction = UIAlertAction(title: "不允許", style: .default, handler: nil)
controller.addAction(allowNotAction)
// 顯示
present(controller, animated: true, completion: nil)

actionSheet (左圖)

由下彈出的警告視窗用.actionSheet — preferredStyle 傳入 .actionSheet

let controllerDown = UIAlertController(title: "此照片會從裝置中刪除", message: "" , preferredStyle: .actionSheet)

按下按鈕選單執行動作

介紹完alert & actionSheet 兩種方式之後,來嘗試讓按鈕執行作動吧~

剛剛在按鈕中有提到,UIAlertAction 的 handler 為設定按下按鈕要執行的程式,在 handler 傳入的 closure 來控制要執行的動作,沒有的話填入nil。

以下為一個小小換圖的的程式碼供參考~

@IBAction func showAlert(_ sender: UIButton) {let controller = UIAlertController(title: "貓貓可愛", message: "是否覺得貓貓很可愛?", preferredStyle: .alert)let okAction = UIAlertAction(title: "是的", style: .default) { (_) in
self
.mylabel.text = "可愛的貓貓唷"
self.myPet.image = UIImage(named: "MyCat")
self.mylabel.isHidden = false
}
let noAction = UIAlertAction(title: "我比較喜歡狗", style: .default) { (_) in
self
.mylabel.text = "我要換成狗狗"
self.myPet.image = UIImage(named: "MyDog")
self.mylabel.isHidden = false
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)controller.addAction(okAction)
controller.addAction(noAction)
controller.addAction(cancelAction)
present(controller, animated: true, completion: nil)
}

效果如下~

增添文字輸入框

使用UIAlertController.addTextField()加上文字輸入框。placeholder調整文字輸入框內的提示文字,用UITextField也能做其他屬性的調整。

像是密碼的部分,可以使用.isSecureTextEntry 隱藏輸入文字來保密密碼。

let controller = UIAlertController(title: "登入", message: "請輸入帳號與密碼" , preferredStyle: .alert)controller.addTextField { (textField) in
textField.placeholder = "帳號"
}
controller.addTextField { (textField) in
textField.placeholder = "密碼"
textField.isSecureTextEntry = true
}

By the way

其他注意事項!容易被忽略的小細節!

  • 由下而上的選單 不能加入輸入框
  • 使用Cancel按鈕的形式,那樣選項它會是在最底下
  • 一個警告視窗內,只能有一個Cancel按鈕的形式

--

--

Anny
Anny

Written by Anny

If You Think You Can, You Can!

No responses yet