
Photo by
marikooota
[Swift]アラート表示方法
Storyboardを使用した場合に画面にアラートを表示する方法を紹介。
まずはソースコード
@IBAction func addButtonPressed(_ sender: UIBarButton) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add", style: .default) { action in
// アラート内のAddボタン押下時処理
}
alert.addTextField { alertTextField in
alertTextField.placeholder = "Create new category"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
NavigationBarにAddボタンを配置し、Addボタンをタップしたときにアラートを表示するというもの。

UIAlertControllerを使う
UIAlertControllerを生成し、presentにUIAlertControllerを指定することでアラートの表示が可能。
UIAlertActionでアクションを設定する
UIAlertActionを生成し、引数のaction(上記トレイリングクロージャ)にボタンタップ時の処理を指定することが可能。
あとはUIAlertControllerにUIAlertActionを追加すれば、有効になる。
最後に
簡単にできた。SwiftUIでの実装方法は別の機会に・・・