
上図のような、UIAlertControllerでポップアップを表示させて、ユーザーがポップアップ内のテキストフィールドに入力後、その文字列を使う処理を行う実装はiPhoneアプリ開発において欠かせないものです。
今回は、UIAlertControllerとUIAlertActionを使って、その実装を行います!
ソース
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@IBAction func onButtonTapped(_ sender: Any) { var uiTextField = UITextField() let ac = UIAlertController(title: "タイトルが入ります", message: "", preferredStyle: .alert) let aa = UIAlertAction(title: "OK", style: .default) { (action) in print(uiTextField.text!) } ac.addTextField { (textField) in textField.placeholder = "メモ" uiTextField = textField } ac.addAction(aa) present(ac, animated: true, completion: nil) } |
ソース自体はこのような形です。
- UIAlertControllerにaddTextFieldでテキストフィールドを追加する。
- そのテキストフィールドをグローバルで持っているuiTextFieldに紐付ける
- UIAlertAction内でuiTextFieldをprintする
- UIAlertActionをUIAlertControllerにaddActionで登録する
非常にシンプルな処理になりました!
あとは、printではなく、任意の処理を書いていけば、ポップアップでユーザーが入力した文字列を自由にシステム内で使うことができます!