
こういったアラート画面でユーザーに選択肢を提示する機能がUIAlertControllerです。
今回は、この機能の実装方法を解説いたします!
ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showAlert() } func showAlert() { let alert = UIAlertController(title: "タイトルを表示", message: "はい?いいえ?", preferredStyle: .alert) let yesAction = UIAlertAction(title: "はい", style: .default, handler: { (UIAlertAction) in print("「はい」が選択されました!") }) let noAction = UIAlertAction(title: "いいえ", style: .default, handler: { (UIAlertAction) in print("「いいえ」が選択されました!") }) alert.addAction(noAction) alert.addAction(yesAction) present(alert, animated: true, completion: nil) } } |
上記がViewControllerが呼び出されたタイミングで、【showAlert()】を実行し、アラート画面を表示するソースです。
viewDidLoad()ではなく、viewDidAppear()の中に実行関数を書いている理由は、viewDidLoad()の中でUIAlertControllerをpresentしてしまうと、【whose view is not in the window hierarchy!】というエラーが発生してしまうからです。
ソース解説
実装は非常にシンプルで、
- alert変数に UIAlertController(title: String, message: String, preferredStyle: .alert)を格納
- yesAction,noActionに UIAlertAction(title: String, style: .default, handler: 実行したい内容が入ったクロージャ)を格納
- yesActionとnoActionをalert変数にadd
- alert変数に格納されているUIAlertControllerをpresentで描写
これだけです!
非常にシンプルに記述できるかつ、汎用的な機能ですので、iphoneアプリ開発で有効な手段になりそうですね!