LoginSignup
71
74

More than 5 years have passed since last update.

[iOS8] SwiftでUIAlertController(アラート)を使うサンプルコードと解説

Posted at

ios8からUIAlertViewやUIActionSheetがdeprecated(非推奨)になりました。
それの代わりとして今後はUIAlertControllerを使うことになります。

今回はその使い方や注意事項をサンプルコードを元に解説していきたいと思います。

サンプルコードはこちら
https://github.com/eversense/Swift-UIAlertController-Example

ボタンを押したら単純なアラートを出す

@IBAction func alertBtn(sender: UIButton) {
    let alertController = UIAlertController(title: "Hello!", message: "This is Alert sample.", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(defaultAction)

    presentViewController(alertController, animated: true, completion: nil)
}

上記のようなコードで、下記のような通常のアラートを出すことができます。

iOS Simulator Screen Shot 2014.09.30 12.21.22

下部から出てくるActionSheet

@IBAction func actionSheetBtn(sender: AnyObject) {
        let alertController = UIAlertController(title: "Hello!", message: "This is ActionSheet sample.", preferredStyle: .ActionSheet)

        let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(defaultAction)

        //For ipad And Univarsal Device
        alertController.popoverPresentationController?.sourceView = sender as UIView;
        alertController.popoverPresentationController?.sourceRect = CGRect(x: (sender.frame.width/2), y: sender.frame.height, width: 0, height: 0)

        presentViewController(alertController, animated: true, completion: nil)
    }

2行目のpreferredStyleにActionSheetを指定することで利用できます。

※ipadの場合にはpopoverPresentationControllerで位置指定を
注意していただきたいのが7〜9行目のところですが、ipadにも対応するUnivarsalなアプリを作る場合は、7行目からあるようなpopoverPresentationControllerでの表示位置の指定が必要になります。この記述がなかった場合、ipadで実行するとクラッシュすることになります。
iphoneに関してはpopoverPresentationControllerの記述をしても影響はありませんし、iphone開発のみでしたらこの部分は削除して構いません。

iOS Simulator Screen Shot 2014.09.30 12.36.27

アラートで選択肢を表示する

@IBAction func choiceBtn(sender: UIButton) {
        let alertController = UIAlertController(title: "Hello!", message: "This is Alert sample.", preferredStyle: .Alert)
        let otherAction = UIAlertAction(title: "OK", style: .Default) {
            action in println("pushed OK!")
        }
        let cancelAction = UIAlertAction(title: "CANCEL", style: .Cancel) {
            action in println("Pushed CANCEL!")
        }

        alertController.addAction(otherAction)
        alertController.addAction(cancelAction)
        presentViewController(alertController, animated: true, completion: nil)
    }

選択肢を増やす場合は、 UIAlertActionでアクションを生成して、addActionで追加すれば簡単に追加出来ます。このサンプルではOKかキャンセルを選択した後、ログに出力しています。

iOS Simulator Screen Shot 2014.09.30 12.54.40

複数の選択肢を持たせる

上記とほぼ同じになります。addAdctionで選択肢を増やしていくことが可能です。

    @IBAction func selectBtn(sender: UIButton) {
        let alertController = UIAlertController(title: "Hello!", message: "This is Alert sample.", preferredStyle: .ActionSheet)
        let firstAction = UIAlertAction(title: "First", style: .Default) {
            action in println("Pushed First")
        }
        let secondAction = UIAlertAction(title: "Second", style: .Default) {
            action in println("Pushed Second")
        }
        let cancelAction = UIAlertAction(title: "CANCEL", style: .Cancel) {
            action in println("Pushed CANCEL")
        }

        alertController.addAction(firstAction)
        alertController.addAction(secondAction)
        alertController.addAction(cancelAction)

        //For ipad And Univarsal Device
        alertController.popoverPresentationController?.sourceView = sender as UIView;
        alertController.popoverPresentationController?.sourceRect = CGRect(x: (sender.frame.width/2), y: sender.frame.height, width: 0, height: 0)
        alertController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up

        presentViewController(alertController, animated: true, completion: nil)
    }

iOS Simulator Screen Shot 2014.09.30 12.54.45

入力フォームをダイアログで表示する

idとパスワードを入力させるようなフォームを表示するサンプルです。

    @IBAction func inputFieldBtn(sender: UIButton) {
        var inputTextField: UITextField?
        var passwordField: UITextField?

        let alertController: UIAlertController = UIAlertController(title: "Login", message: "Input your ID and Password", preferredStyle: .Alert)

        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
            println("Pushed CANCEL")
        }
        alertController.addAction(cancelAction)

        let logintAction: UIAlertAction = UIAlertAction(title: "Login", style: .Default) { action -> Void in
            println("Pushed Login")
            println(inputTextField?.text)
            println(passwordField?.text)
        }
        alertController.addAction(logintAction)

        alertController.addTextFieldWithConfigurationHandler { textField -> Void in
            inputTextField = textField
            textField.placeholder = "ID"
        }
        alertController.addTextFieldWithConfigurationHandler { textField -> Void in
            passwordField = textField
            textField.secureTextEntry = true
            textField.placeholder = "password"
        }

        presentViewController(alertController, animated: true, completion: nil)
    }

2〜3行目:まず初めにフォームで入力した値を取得するためにUITextField型の変数を用意しておきます。

19行目〜:addTextFieldWithConfigurationHandlerでフィールドを追加していきます。
その際2〜3行目で用意した変数に、textFieldを代入しておき後で取得出来るように準備しておきましょう。

25行目:パスワード入力の場合はtextField.secureTextEntry = trueを指定することで、入力内容が非表示になります。

iOS Simulator Screen Shot 2014.09.30 12.54.51

いかがでしたでしょうか?swiftからはよりシンプルな記述でアラートを表示出来るようになりました。使用頻度も多いと思いますので、UIAlertControllerのテンプレートとして下記サンプルを活用して頂ければ幸いです。

サンプルコードはこちら
https://github.com/eversense/Swift-UIAlertController-Example

71
74
0

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
71
74