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