開発環境
- Swift5
- Xcode 11.5
- iOS 13.5
この記事でわかること
- アラートの表示方法
- ボタンの追加方法
- キャンセルボタンの追加方法
- アクションシートの表示方法
アラートの表示
下記のように、UIAlertControllerをインスタンス化し、引数に必要な項目を入れます。
present関数の第1引数にインスタンス化したUIAlertControllerを追加して実行してみましょう。
let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
present(alert, animated: true, completion: nil)
実行結果

アラートにボタンを追加
アラートにタイトルとメッセージだけしかないとアラートを閉じることができないので、
最低限1つのボタンは必要です。
試しに、OKボタンを追加してみます。
UIAlertActionをインスタンス化し、タイトルとスタイルを設定します。
波カッコ({})の中には、OKボタンが押された時に実行したい処理を記述します。
ここではひとまずアラートを閉じる処理を書いています。
let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
//ここから追加
let ok = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(ok)
//ここまで追加
present(alert, animated: true, completion: nil)
実行結果

アラートにキャンセルボタンを追加
キャンセルボタンは、UIAlertActionのstyleを.cancelに変更するだけです。
キャンセルボタンが押された時の処理は、基本的にアラートを閉じるだけなので、以下のような記述となります。
let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
//ここから追加
let cancel = UIAlertAction(title: "キャンセル", style: .cancel) { (acrion) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(cancel)
//ここまで追加
alert.addAction(ok)
present(alert, animated: true, completion: nil)
実行結果

アクションシートの表示方法
UIAlertControllerをインスタンス化するときに、「preferredStyle」の値を「.actionSheet」にするだけでアラート表示がアクションシートに変わります。
let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .actionSheet)//←ここを変更
let ok = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
let cancel = UIAlertAction(title: "キャンセル", style: .cancel) { (acrion) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(cancel)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
実行結果

ABOUT ME

株式会社Playgroundのサービス
- 無料・簡単・片手でホームページを作成できる自社サービス Rakwi
- Web制作とアプリ開発を学べるオンラインプログラミング講座 Upstairs
- 開発,DX推進支援サービス スタートアッププラン