LoginSignup
1
1

More than 3 years have passed since last update.

【Swift】UIAlertControllerを使ってアラートを出してみる

Posted at

概要

UIAlertControllerを使ってボタンをタップした時にアラートを表示する

開発環境

Xcode 12.4
Swift 5.3.2
iOS 14.4

表示スタイル

  • alert
  • actionSheet

    の2種類

alert

//ボタンをタップした時の処理
@IBAction func buttonTapped(_ sender: Any) {
   let ac = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) //インスタンス生成
   ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) //アラートアクションを追加
   present(ac, animated: true, completion: nil) //アラートを表示
}

スクリーンショット 2021-04-13 14.37.15.png
handlerに何も記述していないのでタップしても何も起こらない
”OK”の部分の選択肢はaddActionで追加できる

ac.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))

スクリーンショット 2021-04-13 14.57.50.png

actionSheet

下から出てくるスタイル
preferredStyle.actionSheetに変更するだけ

  @IBAction func buttonTapped(_ sender: Any) {
        let ac = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title: "1", style: .default, handler: nil))
        ac.addAction(UIAlertAction(title: "2", style: .default, handler: nil))
        ac.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
        present(ac, animated: true, completion: nil)
    }

スクリーンショット 2021-04-13 15.14.18.png

ボタンスタイル

ac.addAction(UIAlertAction(title: "", style: .default, handler: nil))

この中のstyleを変更するとボタンのタイプを変えることができる

style 表示
.default 標準文字
.destructive 赤文字
.cancel 太字、一番下に配置

スクリーンショット 2021-04-13 16.13.00.pngスクリーンショット 2021-04-13 16.13.37.png

1
1
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
1
1