📌 基本構文
let alert = UIAlertController(title: "確認", message: "削除してもよろしいですか?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "削除", style: .destructive, handler: { _ in
print("削除されました")
}))
present(alert, animated: true, completion: nil)
このように、アラートは UIAlertController で作成し、present() で表示します。
🛠 スタイルの種類
.alert:中央に表示されるアラート(注意喚起や確認など).actionSheet:画面下からスライド表示(選択肢の提示に使う)
// アクションシート例
let sheet = UIAlertController(title: "共有", message: "どの方法で共有しますか?", preferredStyle: .actionSheet)
sheet.addAction(UIAlertAction(title: "メール", style: .default, handler: nil))
sheet.addAction(UIAlertAction(title: "コピー", style: .default, handler: nil))
sheet.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
present(sheet, animated: true, completion: nil)
🎯 アクションの種類(UIAlertAction.Style)
.default:通常の選択肢(青ボタン).cancel:キャンセルボタン(太字、1つのみ推奨).destructive:警告・破壊的操作(赤ボタン)
📋 使用例:名前入力付きアラート
let alert = UIAlertController(title: "名前入力", message: nil, preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "名前を入力してください"
}
let ok = UIAlertAction(title: "OK", style: .default) { _ in
let name = alert.textFields?.first?.text ?? ""
print("入力された名前: \(name)")
}
alert.addAction(ok)
alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
このように、テキストフィールドを追加することで、ユーザー入力を受け取ることもできます。
📚 参考リンク
✅ ユーザーと対話するアプリには欠かせない UIAlertController を、しっかり活用できるよ