はじめに
ボタンを押した時の表示されるアラートについて、基本的なことをまとめた技術メモです。
ご指摘等ございましたら、コメント、編集リクエストなどで教えていただけると幸いです。
開発環境
- iOS15
- Swift5
- Xcode 13
アラートを表示(Alert/ActionSheet)
Alert
サンプルコード。
let alert: UIAlertController = UIAlertController(title: "Alert表示", message: "hoge", preferredStyle: .alert)
//OKボタン
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("OK")
})
//キャンセルボタン
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .default, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("キャンセル")
})
//UIAlertControllerにActionを追加
alert.addAction(defaultAction)
alert.addAction(cancelAction)
//Alertを表示
present(alert, animated: true, completion: nil)
ActionSheet
let alert: UIAlertController = UIAlertController(title: "Alert表示", message: "hoge", preferredStyle: .alert)
を actionSheet
に変更するだけです。
そして、置き換えたのが、以下のようなコードになります。
let alert: UIAlertController = UIAlertController(title: "Alert表示", message: "hoge", preferredStyle: UIAlertController.Style.actionSheet)
//OKボタン
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("OK")
})
//キャンセルボタン
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .default, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("キャンセル")
})
//UIAlertControllerにActionを追加
alert.addAction(defaultAction)
alert.addAction(cancelAction)
//Alertを表示
present(alert, animated: true, completion: nil)
ボタンスタイル
表示については、以下の種類を選択できます。
UIAlertActionStyle | 説明 |
---|---|
default | 文字:標準/複数指定可 |
cancel | 文字:ボールド/複数指定不可/最下部に位置固定 |
destructive | 文字:赤文字/複数指定可 |
Alert
ActionSheet
以下は、Alert のサンプルコード。
let alert: UIAlertController = UIAlertController(title: "Alert表示", message: "hoge", preferredStyle: .alert)
//defaultボタン
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("default")
})
//cancelボタン
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .cancel, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("cancel")
})
//destructiveボタン
let destructiveAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: .destructive, handler: {
//ボタンが押された時の処理
(action: UIAlertAction) -> Void in
print("destructive")
})
//UIAlertControllerにActionを追加
alert.addAction(defaultAction)
alert.addAction(cancelAction)
alert.addAction(destructiveAction)
//Alertを表示
present(alert, animated: true, completion: nil)
参考文献