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


はじめに

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

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

前提

  • 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以外でテキストフィールドを判定する方法はあるのか?