Swift - UIAlertController的簡單使用
記錄一下,方便日后查找
Demo效果如下:

UIAlertController
-
普通提示框
let alertC = UIAlertController.init(title: "溫馨提示", message: "現(xiàn)在開始走運了", preferredStyle: .alert) alertC.addAction(UIAlertAction.init(title: "好的", style: .default, handler: nil)) present(alertC, animated: true, completion: nil)
-
類似刪除操作提示框
let alertC = UIAlertController.init(title: "溫馨提示", message: "確定刪除BUG嗎?", preferredStyle: .alert) alertC.addAction(UIAlertAction.init(title: "刪除", style: .destructive, handler: { (action) in print("刪除") })) alertC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil)) present(alertC, animated: true, completion: nil)
-
帶一個textField提示框
let alertC = UIAlertController.init(title: "添加數(shù)據(jù)", message: nil, preferredStyle: .alert) //添加textField alertC.addTextField { (textField) in //這里對textField進行設(shè)置 textField.placeholder = "請?zhí)砑觾?nèi)容" // textField.backgroundColor = .green//設(shè)置背景色 } alertC.addAction(UIAlertAction.init(title: "確定", style: .default, handler: { (action) in //這里獲取textField的內(nèi)容進行操作 let text = (alertC.textFields?.first)!.text! print("輸入的內(nèi)容:\(text)") //也可以先實例個textField let textF1 = (alertC.textFields?.first)! as UITextField print("輸入的內(nèi)容:\(textF1.text!)") })) present(alertC, animated: true, completion: nil)獲取輸入框的內(nèi)容:
(alertC.textFields?.first)!.text!
-
類似登錄帶兩個textField的提示框
let alertC = UIAlertController.init(title: "登錄", message: nil, preferredStyle: .alert) //添加textField alertC.addTextField { (textField) in //這里對textField進行設(shè)置 textField.placeholder = "輸入帳號" } alertC.addTextField { (textField) in //這里對textField進行設(shè)置 textField.placeholder = "輸入密碼" textField.isSecureTextEntry = true//密文顯示 } alertC.addAction(UIAlertAction.init(title: "登錄", style: .default, handler: { (action) in //這里獲取textField的內(nèi)容進行操作 //輸入的帳號 let text1 = (alertC.textFields?.first)!.text! //輸入的密碼 let text2 = (alertC.textFields?.last)!.text! print("帳號:\(text1)\n密碼:\(text2)") })) alertC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil)) present(alertC, animated: true, completion: nil)- 提示框彈出后自動消失
let alertC = UIAlertController.init(title: "成功", message: nil, preferredStyle: .alert) present(alertC, animated: true, completion: nil) //3秒后提示框消失 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { //提示框消失 alertC.dismiss(animated: true, completion: nil) }
-
ActionSheet
let alertC = UIAlertController.init(title: "溫馨提示", message: "你準備好了嗎?", preferredStyle: .actionSheet) alertC.addAction(UIAlertAction.init(title: "準備好了", style: .destructive, handler: { (action) in print("萬事俱備") })) alertC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil)) present(alertC, animated: true, completion: nil)
附上Demo