はじめに
Swiftでダイアログを表示したかったため、実装方法をまとめました。
基本的なダイアログの表示
UIAlertControllerのインスタンスを作成してpresent関数に渡すことで、ダイアログを表示することができる。
また、OKボタンのようなアクションを追加したい場合は、UIAlertActionのインスタンスを作成し、addActionでアラートに追加する。
let alert = UIAlertController(title: "タイトル", message: "サブタイトル", preferredStyle: .alert)
// アクションの追加
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
// アクションがタップされた時に実行される処理
NSLog("OKがタップされました。")
}))
self.present(alert, animated: true, completion: nil)
TextFieldを追加する
addTextFieldを使うことでダイアログにテキストフィールドを追加することができる。
(ただし、ダイアログにTextFieldを追加したい場合、preferredStyleプロパティをUIAlertController.Style.alertに設定する必要がある。)
let alert = UIAlertController(title: "タイトル", message: "サブタイトル", preferredStyle: .alert)
// TextFieldを追加
alert.addTextField { (textField) in
// TextFieldの設定をする。
textField.placeholder = "テキストを入力してください。"
}
// アクションの追加
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
// アクションがタップされた時に実行される処理
NSLog("OKがタップされました。")
}))
self.present(alert, animated: true, completion: nil)