LoginSignup
25
23

More than 5 years have passed since last update.

Swiftでユーザー名とパスワードを入力させるアラート表示(UIAlertController)

Posted at

はじめに

UIAlertControllerを使用して、UITextFieldをあつかうアラートができるようです。

簡単な例として、ユーザー名とパスワードを入力させるものを作ります。

ios8-textalert.png

前提

  • UIButton@IBActionで以下のコードを呼び出す
  • 入力値を表示するラベルを2つ用意して、@IBOutlet接続しておく(self.user_name,self.passwordの部分)

ユーザー名とパスワードを入力できるアラート

ViewController
var alert = UIAlertController( title:"ユーザー名とパスワード", message: "入力してね",
        preferredStyle: UIAlertControllerStyle.Alert)

alert.addTextFieldWithConfigurationHandler( { (user: UITextField!) -> Void in
    })
alert.addTextFieldWithConfigurationHandler( { (pw: UITextField!) -> Void in
    pw.secureTextEntry = true
    })

alert.addAction(
    UIAlertAction(title: "OK", style: .Default, handler: {
        (action: UIAlertAction!) -> Void in

        let textFields:Array<UITextField>? =  alert.textFields as Array<UITextField>?
        if textFields != nil {
            for textField:UITextField in textFields! {
                // secureTextEntryの状態で判定
                if textField.secureTextEntry == true {
                    // ラベルにパスワード表示
                    self.password.text = textField.text
                } else {
                    // ラベルにユーザー名表示
                    self.user_name.text = textField.text
                }
            }
        }
    })
)

alert.addAction( UIAlertAction(title: "Cancel", style: .Cancel) {
    action in
})

presentViewController(alert, animated: true, completion: nil)

おわりに

  • alert.addActionのブロックがゴチャっとしてしまった
  • secureTextEntry以外でテキストフィールドを判定する方法はあるのか?
25
23
2

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
25
23