LoginSignup
162
152

More than 5 years have passed since last update.

【iOS】【Swift】UIAlertControllerの基本的動作のまとめ

Posted at

iOS8環境から、UIAlertView/UIActionSheetが非推奨になりまして、
UIAlertControllerを利用する事に。

個人的には、delegateではなくblock(クロージャ)にて処理を指定出来るのが
一番ありがたい所ですが、そのあたりを含めて基本的な動きの整理を

まず基本的な考え方として、
UIAlertView/UIActionSheetのようなUIが利用できなくなったわけではなく
それらを、UIAlertController一つで実現する事ができるようになったので、
そのあたりは引数で指定する事になります。

//UIAlertView
let alert:UIAlertController = UIAlertController(title:"alert", 
            message: "alertView",
            preferredStyle: UIAlertControllerStyle.Alert)

//UIActionSheet
let actionSheet:UIAlertController = UIAlertController(title:"sheet",
            message: "actinSheet",
            preferredStyle: UIAlertControllerStyle.ActionSheet)

第三引数であるpreferredStyleで指定。

次に、ボタン及びそれにひもづく処理の指定の仕方についてですが、
それはUIAlertActionを利用する事になります。

こちらも、3種類存在します。
default/cancel/destructive
通常追加した順番にボタンが表示されますが、cancelにおいては
追加した場合、固定で一番下になります。(このあたり仕様も変わらずかと。)

そのため、Cancelのアクションを二つ以上指定すると、落ちます。



//Cancel 一つだけしか指定できない
let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler:{
            (action:UIAlertAction!) -> Void in
                println("Cancel")
})

//Default 複数指定可
let defaultAction:UIAlertAction = UIAlertAction(title: "Default",
            style: UIAlertActionStyle.Default,
            handler:{
            (action:UIAlertAction!) -> Void in
                println("Default")
})


//Destructive 複数指定可
let destructiveAction:UIAlertAction = UIAlertAction(title: "Destructive",
            style: UIAlertActionStyle.Destructive,
            handler:{
            (action:UIAlertAction!) -> Void in
                println("Destructive")
})

//AlertもActionSheetも同じ
alert.addAction(cancelAction)
alert.addAction(defaultAction)
alert.addAction(destructiveAction)


//表示。UIAlertControllerはUIViewControllerを継承している。
presentViewController(alert, animated: true, completion: nil)

実行例:alert
スクリーンショット 2014-09-28 1.47.25.png

実行例:actionSheet
スクリーンショット 2014-09-28 1.48.43.png

162
152
3

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
162
152