やったこと
- 1ボタンのアラート、2ボタンのアラート、テキストフィールド付きアラートを出す。
アラートを出すUIAlertViewが、Swiftで非推奨とかで、本の通りにできなくなった。
UIAlertViewを使ってダイアログの表示だけは出来る。ボタンを押した時の処理を実装するのが、UIAlertControllerを使わないと出来ない。
うそです。できました。教えて頂きました!
コード
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// アラートを表示
@IBAction func openAlert(sender: UIButton) {
// UIAlertControllerを作成する.
let myAlert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .Alert)
// OKのアクションを作成する.
let myOkAction = UIAlertAction(title: "OK", style: .Default) { action in
println("Action OK!!")
println("Action OK!!")
}
// OKのActionを追加する.
myAlert.addAction(myOkAction)
// UIAlertを発動する.
presentViewController(myAlert, animated: true, completion: nil)
}
@IBAction func openTwoAlert(sender: UIButton) {
// UIAlertControllerを作成する.
let myAlert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .Alert)
// OKのアクションを作成する.
let myOkAction = UIAlertAction(title: "OK", style: .Default) { action in
println("Action OK!!")
}
// OKのActionを追加する.
myAlert.addAction(myOkAction)
// キャンセルのアクションを作成する.
let myCclAction = UIAlertAction(title: "キャンセル", style: .Default) { action in
println("キャンセル")
}
// キャンセルのActionを追加する.
myAlert.addAction(myCclAction)
// UIAlertを発動する.
presentViewController(myAlert, animated: true, completion: nil)
}
@IBAction func openTextAlert(sender: UIButton) {
// UIAlertControllerを作成する.
let myAlert = UIAlertController(title: "パスワードを入力して下さい。", message: "半角英数6文字以上", preferredStyle: .Alert)
// OKのアクションを作成する.
let myOkAction = UIAlertAction(title: "OK", style: .Default) { action in
println("Action OK!!")
}
// OKのActionを追加する.
myAlert.addAction(myOkAction)
// キャンセルのアクションを作成する.
let myCclAction = UIAlertAction(title: "キャンセル", style: .Default) { action in
println("キャンセル")
}
// キャンセルのActionを追加する.
myAlert.addAction(myCclAction)
//textfiledの追加
myAlert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
text.placeholder = "Password"
// 入力文字を隠す
text.secureTextEntry = true
})
// UIAlertを発動する.
presentViewController(myAlert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
参考サイト
クロージャ(action in ...と言った書き方について)
http://qiita.com/yimajo/items/32a5209bd73580d283a1
テキストフィールド付きアラートで入力チェックしようと思ったらこちらを参考にする
https://sites.google.com/a/gclue.jp/swift-docs/ni-yinki100-ios/uikit/051-uialertcontrollerde-wen-zi-shu-zhi-xianwo-shekeru
逆引きSwift便利すぎてやる気なくなった。
その他
-
ドキュメントウィンドウの表示
Xcodeでコードのドキュメントを見るためには、メニューで「Window - Document..」を押す。
補完候補で「More」ってリンクが出てきたら押すとドキュメントに行くんだけど、それをもう一回表示させようとしたら、上の方法。 -
分岐できない
アラートで、押したボタンのインデックスで、分岐させる方法を使えないのは、わかりにくいのか、わかりやすいのか。
アラートを使わせない方向だろうか。