LoginSignup
8
9

More than 3 years have passed since last update.

ダイアログを表示する

Posted at

本記事は「デジタルサイネージアプリ「Sign!」(iOS版)とその実装機能の紹介」の子記事です。

目的

複数の選択肢を持つダイアログ(UIAlertController)を開き、特定の選択肢を選んだときに、何らかの処理を行うためのコードを紹介します。

開発・実行環境

  • 開発環境:macOS、Xcode(9~10)、Swift(4~5)
  • 実行環境:iOS 11以上

コード

まず、コード例と、実際に表示されるダイアログのイメージを紹介します。
便宜上、ViewControllerのviewDidAppeared()でダイアログを生成し、表示させます(アプリを起動するといきなりダイアログが開きます)。

ViewController.swift
override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  // ダイアログ(AlertControllerのインスタンス)を生成します
  //   titleには、ダイアログの表題として表示される文字列を指定します
  //   messageには、ダイアログの説明として表示される文字列を指定します
  let dialog = UIAlertController(title: "Dialog Title", message: "Message is here", preferredStyle: .alert)
  // 選択肢(ボタン)を2つ(OKとCancel)追加します
  //   titleには、選択肢として表示される文字列を指定します
  //   styleには、通常は「.default」、キャンセルなど操作を無効にするものは「.cancel」、削除など注意して選択すべきものは「.destructive」を指定します
  dialog.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  dialog.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
  // 生成したダイアログを実際に表示します
  self.present(dialog, animated: true, completion: nil)
}

実行するとこのようなダイアログが表示されます。
1

なお、ダイアログを生成する行の「preferredStyle」に「.actionSheet」を指定すると、iPhoneの場合は、以下のようなメニューが画面下からせり上がるように表示されます。用途に合わせて使い分けてください。
2

ところで、このコードのままでは、「OK」や「Cancel」を選んでも、単にダイアログが閉じるだけで、何の処理もされません。選択肢をタップすると何らかの処理をする場合は、addAction()のhandlerをnilにせず、コードを書く必要があります。
ここでは、「OK」をタップすると、画面の色がランダムに変わるようにしてみます(実用性はありませんが)。
※「OK」に該当するaddAction()のみ記述しています。

ViewController.swift
dialog.addAction(UIAlertAction(title: "OK", style: .default,
  handler: { action in
    self.view.backgroundColor = UIColor(
      red: CGFloat(Float.random(in: 0.0 ... 1.0)),
      green: CGFloat(Float.random(in: 0.0 ... 1.0)),
      blue: CGFloat(Float.random(in: 0.0 ... 1.0)),
      alpha: 1.0)
  }))

以上です。

8
9
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
8
9