警告提示框(UIAlertController)的用法
阿新 • • 發佈:2019-01-10
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 建立
let alertController = UIAlertController(title: "提示", message: "你確定要離開?" , preferredStyle:.Alert)
// 設定2個UIAlertAction
let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
let okAction = UIAlertAction(title: "好的", style: .Default) { (UIAlertAction) in
print("點選了好的")
}
// 新增
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// 彈出
self.presentViewController(alertController, animated: true, completion: nil)
}
}
// 除了彈出,還可以使用底部向上滑出的樣式
// 注意:如果上拉選單中有『取消』按鈕的話,那麼它永遠都會出現在選單的底部,不管新增的次序如何
// 建立
// preferredStyle 為 ActionSheet
let alertController = UIAlertController(title: "儲存或刪除資料", message: "刪除資料將不可恢復" , preferredStyle:.ActionSheet)
// 設定2個UIAlertAction
let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
let deleteAction = UIAlertAction(title: "刪除", style: .Destructive, handler: nil)
let saveAction = UIAlertAction(title: "儲存", style: .Default, handler: nil)
// 新增到UIAlertController
alertController.addAction(cancelAction)
alertController.addAction(saveAction)
alertController.addAction(deleteAction)
// 彈出
self.presentViewController(alertController, animated: true, completion: nil)
/*
新增任意數量的文字輸入框(比如可以用來實現登入框)
*/
let alertController = UIAlertController(title: "系統登入", message: "請輸入使用者名稱和密碼", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField:UITextField) in
textField.placeholder = "使用者名稱"
}
alertController.addTextFieldWithConfigurationHandler { (textField:UITextField) in
textField.placeholder = "密碼"
textField.secureTextEntry = true
}
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default) { (UIAlertAction) in
let login = alertController.textFields![0]
let pwd = alertController.textFields![1]
print("使用者名稱:\(login.text) 密碼:\(pwd.text)")
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// 彈出
self.presentViewController(alertController, animated: true, completion: nil)