はじめに
ちょっと何かを入力させる時に、いちいちUI配置したりしなくて済むので便利で使える。
環境
Xcode 12.3
コード
let title = "Title"
let msg = "Message"
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
//OKボタンの設定
let okAction = UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) -> Void in
//テキストフィールド付きアラートでOKボタンが押された時の処理
//テキストフィールドに入力された値をオプショナルバインディングして取り出す
if let str = alert.textFields?[0].text{
print(str)
}
})
alert.addAction(okAction)
//キャンセルボタンの設定
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
//テキストフィールドの追加
alert.addTextField(configurationHandler: {(textField:UITextField!) -> Void in
// ここでテキストフィールドのカスタマイズができる
textField.placeholder = ""
textField.keyboardType = .default
})
// 複数追加したいならその数だけ書く
// alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in
// textField.placeholder = "テキスト"
// })
//アラートを画面に表示
self.present(alert, animated: true, completion: nil)
}
textFieldを複数使用したい時はaddTextFieldを複数書く