[Swift] 使用AlertView 顯示警告訊息
1.單純跳出警示,按下確定後不做任何動作
//如果token是空值
if (User.token.isEmpty){
//設定UIAlertController的title,message
let alertController = UIAlertController(title: "並未登入", message: "測試內容", preferredStyle: .alert)
//設定action按鈕
let okAction = UIAlertAction(title: "確定", style: .default)
//將action加入UIAlertController
alertController.addAction(okAction)
//彈出UIAlertController
self.present(alertController, animated: true, completion: nil)
return
}

2.跳出可選擇的警示,並加入按下確定後執行的動作
//設定UIAlertController的title,message
let controller = UIAlertController(title: "是否登出", message: "", preferredStyle: .alert)
//設定ok的action按鈕,並加入按下後的動作
let okAction = UIAlertAction(title: "確定", style: .default){(_) in
User.token = ""
let logoutController = UIAlertController(title: "帳號已登出", message: "", preferredStyle: .alert)
let logoutOkAction = UIAlertAction(title: "確定", style: .default)
logoutController.addAction(logoutOkAction)
self.present(logoutController, animated: true, completion: nil)
}
//將action加入UIAlertController
controller.addAction(okAction)
//設定cancel的action按鈕
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//將action加入UIAlertController
controller.addAction(cancelAction)
//彈出UIAlertController
self.present(controller, animated: true, completion: nil)
return

