1. TextFieldを乗せたAlertを生成
let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "テキストを入力"
}
let completedAction = UIAlertAction(title: "完了", style: .default) { (action) in
//完了ボタンがタップされたときの処理
}
let cancelAction = UIAlertAction(title: "キャンセル", style: .cancel, handler: nil)
alert.addAction(completedAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
2. 入力値を取り出す
let completedAction = UIAlertAction(title: "完了", style: .default) { (action) in
//1. alertのtextFieldsから特定のTextFieldを取り出します
if let textFieldInAlert = alert.textFields?.first {
//2. あとは通常のTextFieldの操作と同じです
let text = textFieldInAlert.text ?? ""
print(text)
}
}
以上