UIAlertControllerを実装する

簡単にアラートを表示する

アラートはUIKit標準機能としてUIAlertControllerが用意されています。 まずはこれを使っておけば間違いはありません。使い方としては、何かアクションを行う場合にユーザーにアクションを求めたり、エラー時のメッセージ表示などです。簡単な「OK」だけのアラートや、アクションを行う場合のキャンセルを備えた「OK」「キャンセル」アラート、複数の選択肢を備えたものなどアプリにおいて必要なアラートを実装することができます。

ここでは、プロジェクトを新規作成して他の実装がないViewController.swiftでコードを記述しています。 コードに予め用意されているViewDidLoad内での記述ではアラート表示はできないので、viewDidAppear(画面が表示されたときに実行されるメソッド)で実装を行いアラートを表示させてみます。

/images/uploads/20200505030614.png

ViewController.swiftのコード全体は以下のようになります。 UIAlertViewはストーリーボードは絡んでないのでこのままコピペでOKです。

import UIKit

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
  }
  
  override func viewDidAppear(_ animated: Bool) {
    
    // アラートビューの定義
    let alertController:UIAlertController =
      UIAlertController(title:"Alert",
                        message: "This is test alert",
                        preferredStyle: .alert)
    
    // OKボタンの定義
    let defaultAction:UIAlertAction =
      UIAlertAction(title: "OK",
                    style: .default,
                    handler:{
                      (action:UIAlertAction!) -> Void in
                      // OKボタンを押した時の処理
                      print("OK")
      })
    
    // キャンセルボタンの定義
    let cancelAction:UIAlertAction =
      UIAlertAction(title: "Cancel",
                    style: .cancel,
                    handler:{
                      (action:UIAlertAction!) -> Void in
                      // キャンセルボタンを押した時の処理
                      print("Cancel")
      })
    
    // アラートビューへアクションを追加する
    alertController.addAction(cancelAction)
    alertController.addAction(defaultAction)
    
    // アラートビューを表示する
    self.present(alertController, animated: true, completion: nil)
    
  }
  
}

アプリを実行する

ここまでできたらXcodeの「▷」を押してアプリを実行してみましょう。 以下のような画面になれば実装完了です。

/images/uploads/20200505031437.png

アラートに対して選択肢をタッチすればデバッグプリントに出力がされます。 アラートを選択した後の処理をコード内に記述すれば機能させることが可能となります。

/images/uploads/20200505031832.png

今回はviewDidAppearメソッドの中に書いて実行直後にアラートを表示するというスタイルでの実装でしたが、 実際のアプリ開発では上記コードをアラートを表示したい機能や、エラー時の処理の部分に実装となります。

応用

「OK」「キャンセル」以外の選択肢を実装する

「OK」「キャンセル」以外にも複数のボタンを存在させることができます。

設定できるスタイルは、以下の3つがあります。

  • .default 標準スタイルのボタン
  • .destructive 赤文字の否定的ボタン
  • .cancel キャンセルボタン

そして、addActionメソッドは、スタイルが.cancelのものが一番下に来ます。 その他のスタイルのものはaddが書かれた順にアラートに表示されます。

    // アラートビューの定義
    let alertController:UIAlertController =
      UIAlertController(title:"Alert",
                        message: "This is test alert",
                        preferredStyle: .alert)
    
    // OKボタンの定義
    let defaultAction:UIAlertAction =
      UIAlertAction(title: "OK",
                    style: .default,
                    handler:{
                      (action:UIAlertAction!) -> Void in
                      // OKボタンを押した時の処理
                      print("OK")
      })
    
    // 選択肢1の定義
    let selectAction:UIAlertAction =
      UIAlertAction(title: "Other",
                    style: .destructive,
                    handler:{
                      (action:UIAlertAction!) -> Void in
                      // 選択肢1ボタンを押した時の処理
                      print("Other")
      })
    
    
    // キャンセルボタンの定義
    let cancelAction:UIAlertAction =
      UIAlertAction(title: "Cancel",
                    style: .cancel,
                    handler:{
                      (action:UIAlertAction!) -> Void in
                      // キャンセルボタンを押した時の処理
                      print("Cancel")
      })
    
    // アラートビューへアクションを追加する
    alertController.addAction(cancelAction)
    alertController.addAction(defaultAction)
    alertController.addAction(selectAction)

アプリを実行すると、以下のような感じになります。

/images/uploads/20200505034739.png

アラート表示ではなく、アクションシート表示にする

この他にアラート表示からアクションシートにする方法もあります。画面の下から出てくるようなUIですが、こちらもUIAlertControllrtのスタイルを変更するだけで簡単に実装できます。

/images/uploads/20200505035152.png

    // アラートビューの定義
    let alertController:UIAlertController =
      UIAlertController(title:"Alert",
                        message: "This is test alert",
                        preferredStyle: .actionSheet)  // ← .alertを.actionSheetに変更する
```												

![/images/uploads/20200505035028.png](/images/uploads/20200505035028.png)

アラートコントローラーはアプリを開発する上で必須な機能となりますので、覚えておきましょう。

Category