iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
Mobile Development

ios 的小小實驗室 !系列 第 11

DAY 11 『 UIAlertController 』Part2

昨天分享如何從中間彈出、由下而上彈出 UIAlertController
今天會介紹:

  1. 顯示多個按鈕
  2. 在 alert 裡顯示 TextField

顯示多個按鈕,並設定點選按鈕時做的事情

按了按鈕後,執行{ 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:

  • 參數 preferredStyle :
    .alert:將顯示從中間彈出的視窗。
    .actionSheet:將顯示由下而上彈出的選單視窗。

利用 UIAlertAction 生成視窗上的按鈕

  • style :可控制文字的樣式顏色
    .default:預設( 藍字 )
    .destructive:紅字

  • handler 傳入的 closure :控制點選按鈕要做的事情

利用 addAction() 加入按鈕; 呼叫幾個 addAction,即可加入幾個按鈕。

底部提示框不能加入輸入框。

如果有加入Cancel按鈕到底部提示框,它會永遠在最底下一個。


這樣就學會 UIAlertController 的使用啦!明天會有新的實作分享,敬請期待!


上一篇
DAY 10 『 UIAlertController 』Part1
下一篇
DAY 12『 利用安裝套件管理工具 ( CocoaPods ) 下載資料庫( Realm Studio ) 』
系列文
ios 的小小實驗室 !30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言