LoginSignup
0
2

More than 3 years have passed since last update.

TextField付きアラート

Posted at

はじめに

ちょっと何かを入力させる時に、いちいちUI配置したりしなくて済むので便利で使える。

完成形
スクリーンショット 2021-01-05 15.23.20.png

環境

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を複数書く

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2