概要
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) //アラートを表示
}
handler
に何も記述していないのでタップしても何も起こらない
”OK”の部分の選択肢はaddAction
で追加できる
ac.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
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)
}
ボタンスタイル
ac.addAction(UIAlertAction(title: "", style: .default, handler: nil))
この中のstyle
を変更するとボタンのタイプを変えることができる
style | 表示 |
---|---|
.default | 標準文字 |
.destructive | 赤文字 |
.cancel | 太字、一番下に配置 |