🔔 UIAlertControllerとは?

UIAlertController は、iOSアプリで アラートアクションシート を表示するためのクラスです。ユーザーに注意を促したり、選択肢を与えるときによく使われます。


…読み込み中…

📌 基本構文

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() で表示します。


🛠 スタイルの種類

// アクションシート例
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)


📋 使用例:名前入力付きアラート

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 を、しっかり活用できるよ