Swift UIAlertControllerの初心者向け使い方ガイド


なかなか時間がとれていませんが、Swiftの勉強をしている中でiOS 8から、「UIAlertView」がdeprecated(廃止予定) になったことを知りました。
新しい「UIAlertController」への移行が推奨されているそうです!

今回は今後使いそうな「UIAlertController」の書き方を知ったので俺得スニペットです!


🐯 SwiftでUIAlertControllerを呼び出す

var alertController = UIAlertController(title: "sample title", message: "sample message", preferredStyle: .Alert)

// ボタン 1を作成
let firstAction = UIAlertAction(title: "button 1", style: .Default) {
action in println("button 1 が押されました")
}

// ボタン 2を作成
let secondAction = UIAlertAction(title: "button 2", style: .Default) {
action in println("ボタン 2 が押されました")
}

// ボタンを配置
alertController.addAction(firstAction)
alertController.addAction(secondAction)

// アラートを表示
// 通常の ViewController で呼び出す場合
presentViewController(alertController, animated: true, completion: nil)

// AppDelegate で呼び出す場合
// self.window!.rootViewController!.presentViewController(alertController, animated: true, completion: nil)

😸 参考リンク

Objective-C - iOS8でのダイアログ表示:廃止になるUIAlertViewと推奨されているUIAlertControllerのメリット - Qiita

UIAlertController を AppDelegateで表示する: iPhoneアプリ開発備忘録

🖥 VULTRおすすめ

VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!

📚 おすすめの書籍