1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UIAlertControllerのTextFieldから入力値を取り出す方法

Posted at

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)
            }
        }

以上

1
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?