昨天分享如何從中間彈出、由下而上彈出 UIAlertController
今天會介紹:
顯示多個按鈕,並設定點選按鈕時做的事情
按了按鈕後,執行{ action in }
裡的動作
let alertController = UIAlertController(title: "alert title", message: "alert message", preferredStyle: .alert)
func merge(mergetitle: String, mergestyle: UIAlertAction.Style ,mergehandler: ((UIAlertAction) -> Void)?) {
alertController.addAction(UIAlertAction(title: mergetitle, style: mergestyle, handler: mergehandler))
}
merge(mergetitle: "Ok" , mergestyle: UIAlertAction.Style.default, mergehandler: { action in print("Ok")})
merge(mergetitle: "Cancel" , mergestyle: UIAlertAction.Style.cancel, mergehandler: { action in print("Cancel")})
merge(mergetitle: "Destructive" , mergestyle: UIAlertAction.Style.destructive, mergehandler: { action in print("Destructive")})
present(alertController, animated: true, completion: nil)
在 alert 裡顯示 TextField
按了"確認"的按鈕後,執行print ( phone as Any, password as Any )
let alertController = UIAlertController(title: "登入", message: "輸入電話和密碼", preferredStyle: .alert)
// 參數 configurationHandler 傳入的 closure 設定 text field 的樣式
alertController.addTextField { textField in
textField.placeholder = "電話"
textField.keyboardType = UIKeyboardType.phonePad // 跳出電話鍵盤
}
alertController.addTextField { textField in
textField.placeholder = "密碼"
textField.isSecureTextEntry = true // 密碼隱藏
}
// 必須加上 capture list [unowned controller],避免 reference cycle 造成的記憶體問題
let alertOkAction = UIAlertAction(title: "確認", style: .default) { [unowned alertController] _ in
let phone = alertController.textFields?[0].text
let password = alertController.textFields?[1].text
print(phone as Any, password as Any)
}
alertController.addAction(alertOkAction)
let alertCancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(alertCancelAction)
present(alertController, animated: true, completion: nil)
Hint:
利用 UIAlertAction 生成視窗上的按鈕
style :可控制文字的樣式顏色
.default:預設( 藍字 )
.destructive:紅字
handler 傳入的 closure :控制點選按鈕要做的事情
利用 addAction() 加入按鈕; 呼叫幾個 addAction,即可加入幾個按鈕。
底部提示框不能加入輸入框。
如果有加入Cancel按鈕到底部提示框,它會永遠在最底下一個。
這樣就學會 UIAlertController 的使用啦!明天會有新的實作分享,敬請期待!