LoginSignup
6
1

More than 3 years have passed since last update.

【Swift】 TextFieldのあるAlertを表示させる方法

Last updated at Posted at 2020-05-26

SwiftでTextFieldのあるAlertを表示させる方法。

実装イメージ

このようなタイトル、サブタイトル、入力欄、キャンセル、追加で構成されたAlertを作成して行きます。
スクリーンショット 2020-05-26 14.57.09.png

Storyboard

buttonを押すとAlertが表示されるようにするため、好きな場所にbuttonを1つ追加しましょう。
スクリーンショット 2020-05-26 14.19.46.png

ソースコード

ViewController.Swift
import UIKit

//UITextFieldDelegateを追加する
class ViewController: UIViewController,UITextFieldDelegate {

    //StoryboardのbuttonをAction接続する
    @IBAction func aleat(_ sender: Any) {

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        alert.title = "ここにタイトル"
        alert.message = "メッセージ"

        alert.addTextField(configurationHandler: {(textField) -> Void in
            textField.delegate = self

        })

        //追加ボタン
        alert.addAction(
            UIAlertAction(
                title: "追加",
                style: .default,
                handler: {(action) -> Void in
            self.hello(action.title!)
        })
        )

        //キャンセルボタン
        alert.addAction(
        UIAlertAction(
            title: "キャンセル",
            style: .cancel,
            handler: {(action) -> Void in
                self.hello(action.title!)
        })
        )

        //アラートが表示されるごとにprint
        self.present(
        alert,
        animated: true,
        completion: {
            print("アラートが表示された")
        })
    }

    func hello(_ msg:String){
        print(msg)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

ビルドして確認してみましょう

実装イメージのようなAlertを表示させることができたでしょうか?
title部分は好きな文に変えることでお好みのAlertを表示させることができます。

できたー!という方はLGTM押してくださると僕がめっちゃ喜びます!

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