SwiftUI Alert: The Modern .alert Modifier, Roles, and confirmationDialog
Everything you need to present alerts in SwiftUI the current way — the value/isPresented modifiers, item-driven alerts, text-field alerts, button roles, and action sheets via confirmationDialog. Compilable Swift 6 code, real pitfalls, and iOS 26 notes.
Present alerts in SwiftUI with the view modifier .alert(_:isPresented:) { /* action buttons */ } message: { /* body */ }. Drive it from a Bool @State, or use .alert(_:isPresented:presenting:) / .alert(item:) to carry data. Buttons take a role of .destructive or .cancel, and multi-choice action sheets use .confirmationDialog. The old Alert() struct is deprecated — don't build alerts by returning Alert values anymore.
Variants: Confirm, Text Field
Install the free SwiftUI alert
- Add SwiftKitUI.swift to your app once. It holds the tokens and motion curves.
- Copy SKAlert.swift below into your project. It needs nothing else.
Usage
.skAlert(isPresented: $show, title: "Delete?",
message: "This cannot be undone.",
confirm: .init(title: "Delete", role: .destructive) { delete() })
.skAlert(isPresented: $rename, title: "Rename",
text: $name, placeholder: "New name",
confirm: .init(title: "Save") { save(name) })Full source · 232 lines · MIT
//
// SKAlert.swift
// Swift Kit UI
//
// Requires: SwiftKitUI.swift
//
// A styled alert that can carry a text field — the thing the system alert
// technically supports but gives you no control over.
//
// Presented as an overlay rather than a `.sheet`, so it can be branded and so
// the backdrop dims the actual app instead of the system's flat scrim.
//
// Usage:
// .skAlert(isPresented: $show, title: "Delete?",
// message: "This cannot be undone.",
// confirm: .init(title: "Delete", role: .destructive) { delete() })
//
// .skAlert(isPresented: $rename, title: "Rename",
// text: $name, placeholder: "New name",
// confirm: .init(title: "Save") { save(name) })
//
import SwiftUI
public struct SKAlertAction {
public enum Role: Sendable { case normal, destructive }
public let title: String
public let role: Role
public let handler: () -> Void
public init(title: String, role: Role = .normal, handler: @escaping () -> Void = {}) {
self.title = title
self.role = role
self.handler = handler
}
}
private struct SKAlertModifier: ViewModifier {
@Binding var isPresented: Bool
let title: String
let message: String?
let systemImage: String?
var text: Binding<String>?
let placeholder: String
let confirm: SKAlertAction
let cancelTitle: String?
@FocusState private var fieldFocused: Bool
func body(content: Content) -> some View {
content.overlay {
if isPresented {
ZStack {
Color.black.opacity(0.38)
.ignoresSafeArea()
.transition(.opacity)
.onTapGesture { dismiss() }
card
.transition(.opacity.combined(with: .scale(scale: 0.92)))
}
.skAnimation(.settle, value: isPresented)
.zIndex(10)
}
}
.skAnimation(.settle, value: isPresented)
}
private var card: some View {
VStack(spacing: SK.Space.lg) {
if let systemImage {
Image(systemName: systemImage)
.font(SK.Icon.symbol(SK.Icon.xl))
.foregroundStyle(confirm.role == .destructive ? SK.Palette.danger : SK.Palette.accent)
}
VStack(spacing: SK.Space.xs) {
Text(title)
.font(SK.Type_.headline)
.foregroundStyle(SK.Palette.label)
if let message {
Text(message)
.font(SK.Type_.callout)
.foregroundStyle(SK.Palette.labelSecondary)
.multilineTextAlignment(.center)
}
}
if let text {
TextField(placeholder, text: text)
.font(SK.Type_.body)
.padding(.horizontal, SK.Space.md)
.frame(height: SK.Icon.hitTarget)
.background(SK.Palette.fill, in: RoundedRectangle(cornerRadius: SK.Radius.sm, style: .continuous))
.focused($fieldFocused)
.submitLabel(.done)
.onSubmit(run)
}
HStack(spacing: SK.Space.sm) {
if let cancelTitle {
Button(cancelTitle) { dismiss() }
.buttonStyle(SKButtonStyleShim.secondary)
}
Button(confirm.title, action: run)
.buttonStyle(confirm.role == .destructive
? SKButtonStyleShim.destructive
: SKButtonStyleShim.primary)
}
}
.padding(SK.Space.xl)
.frame(maxWidth: 320)
.skSurface(.elevated, radius: SK.Radius.xl)
.padding(SK.Space.xl)
// Focus the field after the entry animation, not during it — focusing
// mid-transition makes the keyboard race the alert on screen.
.task {
guard text != nil else { return }
try? await Task.sleep(for: .milliseconds(320))
fieldFocused = true
}
}
private func run() {
confirm.handler()
dismiss()
}
private func dismiss() {
fieldFocused = false
isPresented = false
}
}
/// Minimal local button styling.
///
/// SKAlert deliberately does NOT reuse SKButton: a component may depend only on
/// the foundation, never on a sibling, or it stops being installable on its own.
private struct SKButtonStyleShim: ButtonStyle {
enum Kind { case primary, secondary, destructive }
let kind: Kind
static let primary = SKButtonStyleShim(kind: .primary)
static let secondary = SKButtonStyleShim(kind: .secondary)
static let destructive = SKButtonStyleShim(kind: .destructive)
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(SK.Type_.headline)
.foregroundStyle(kind == .secondary ? SK.Palette.label : Color.white)
.frame(maxWidth: .infinity)
.padding(.vertical, SK.Space.md)
.background {
let shape = RoundedRectangle(cornerRadius: SK.Radius.md, style: .continuous)
switch kind {
case .primary: shape.fill(SK.Palette.accent)
case .destructive: shape.fill(SK.Palette.danger)
case .secondary: shape.fill(SK.Palette.fill)
}
}
.scaleEffect(configuration.isPressed ? 0.97 : 1)
.skAnimation(.micro, value: configuration.isPressed)
}
}
extension View {
/// Confirmation alert.
public func skAlert(
isPresented: Binding<Bool>,
title: String,
message: String? = nil,
systemImage: String? = nil,
confirm: SKAlertAction,
cancelTitle: String? = "Cancel"
) -> some View {
modifier(SKAlertModifier(
isPresented: isPresented, title: title, message: message,
systemImage: systemImage, text: nil, placeholder: "",
confirm: confirm, cancelTitle: cancelTitle
))
}
/// Alert with a text field.
public func skAlert(
isPresented: Binding<Bool>,
title: String,
message: String? = nil,
systemImage: String? = nil,
text: Binding<String>,
placeholder: String = "",
confirm: SKAlertAction,
cancelTitle: String? = "Cancel"
) -> some View {
modifier(SKAlertModifier(
isPresented: isPresented, title: title, message: message,
systemImage: systemImage, text: text, placeholder: placeholder,
confirm: confirm, cancelTitle: cancelTitle
))
}
}
#Preview("SKAlert") {
@Previewable @State var confirmShown = false
@Previewable @State var renameShown = false
@Previewable @State var name = "Untitled"
VStack(spacing: SK.Space.md) {
Button("Destructive confirm") { confirmShown = true }
Button("With a text field") { renameShown = true }
Text(name).font(SK.Type_.caption).foregroundStyle(SK.Palette.labelSecondary)
}
.font(SK.Type_.callout)
.foregroundStyle(SK.Palette.accent)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(SK.Palette.surfaceSunken)
.skAlert(
isPresented: $confirmShown,
title: "Delete project?",
message: "This removes every file. It cannot be undone.",
systemImage: "trash.fill",
confirm: .init(title: "Delete", role: .destructive)
)
.skAlert(
isPresented: $renameShown,
title: "Rename",
text: $name,
placeholder: "Project name",
confirm: .init(title: "Save")
)
}
The modern alert modifier
SwiftUI alerts are attached to a view with the .alert modifier rather than constructed as objects. The most common form takes a title, a Bool binding that controls presentation, and two trailing closures — one for the action buttons and one for the message body. When the binding flips to true the system presents the alert; dismissing any button sets it back to false for you, so you rarely toggle it manually on the way out. Keep the title short and put explanatory text in the message closure. If you provide no buttons, SwiftUI supplies a default OK button automatically, but being explicit reads better and lets you attach roles.
struct SaveView: View {
@State private var showConfirmation = false
var body: some View {
Button("Save Draft") { showConfirmation = true }
.alert("Draft Saved", isPresented: $showConfirmation) {
Button("OK", role: .cancel) { }
} message: {
Text("Your draft was stored locally and will sync when you're back online.")
}
}
}Data-driven alerts: presenting: and item:
A raw Bool is fine for a single fixed message, but real apps need the alert to carry data — which row failed, which error was thrown. Two overloads solve this. .alert(_:isPresented:presenting:) hands the non-optional presented value into both closures so you can format a message from it. The item-driven variant, .alert(_:isPresented:presenting:) paired with an optional @State, is ideal for errors: set the optional to a value to present, and SwiftUI clears it on dismiss. This pattern keeps a single alert modifier that adapts to whatever error occurred instead of scattering booleans across your view.
struct AppError: Identifiable {
let id = UUID()
let title: String
let message: String
}
struct UploadView: View {
@State private var activeError: AppError?
var body: some View {
Button("Upload") { attemptUpload() }
.alert(item: $activeError) { error in
Alert(title: Text(error.title), message: Text(error.message))
}
}
private func attemptUpload() {
activeError = AppError(title: "Upload Failed",
message: "Check your connection and try again.")
}
}Text-field alerts and confirmationDialog action sheets
Since iOS 16 you can drop a TextField (or SecureField) directly inside the alert actions closure to collect a short string — a rename, a passcode, a nickname. Bind it to @State and read the value in your confirm button. For presenting several mutually exclusive choices, use .confirmationDialog, the replacement for the deprecated .actionSheet. It renders as a bottom sheet on iPhone and a popover on iPad, supports the same roles, and takes a titleVisibility argument to show or hide the header. Reserve confirmationDialog for 2–4 choices; more than that belongs in a real list or menu.
struct ItemRow: View {
@State private var newName = ""
@State private var showRename = false
@State private var showOptions = false
var body: some View {
VStack {
Button("Rename") { showRename = true }
Button("More Options") { showOptions = true }
}
.alert("Rename Item", isPresented: $showRename) {
TextField("New name", text: $newName)
Button("Save") { /* persist newName */ }
Button("Cancel", role: .cancel) { }
}
.confirmationDialog("Item Options", isPresented: $showOptions, titleVisibility: .visible) {
Button("Duplicate") { }
Button("Delete", role: .destructive) { }
Button("Cancel", role: .cancel) { }
}
}
}Migrating off the deprecated Alert() type
Older SwiftUI code returned Alert values from an .alert(isPresented:content:) closure using Alert(title:message:primaryButton:secondaryButton:). That whole family is deprecated. The migration is mechanical: replace the returned Alert with an actions closure of Buttons and a message closure of Text. Alert.Button.destructive becomes Button(role: .destructive), and .cancel maps to Button(role: .cancel). The payoff is more than three buttons (the old struct capped at two), TextField support, and consistency with .confirmationDialog. If you still see Alert() in a codebase, treat it as tech debt worth clearing during any touch of that file.
- Alert(title:message:dismissButton:) → .alert(title, isPresented:) { Button("OK") { } }
- primaryButton/secondaryButton → two Button views in the actions closure
- .actionSheet → .confirmationDialog
- The new API removes the two-button limit and unlocks text fields
Ship your SwiftUI app in 5 emails
A free 5-part course on the parts that actually stall launches: paywall, auth, onboarding, App Store review, and pricing. No fluff, unsubscribe anytime.
Stop hand-rolling error dialogs
The Swift Kit ships a typed AppError enum bound to a single item-driven alert, so every thrown error surfaces a friendly, localized message with zero boilerplate per screen.
Rather have it done for you? I set up and ship your app from $499. See how
How to present an error alert that carries data
Use an optional @State so the alert both presents and self-clears, and so the message reflects the specific failure.
- 1
Model the error
Create a small Identifiable struct or enum that holds a user-facing title and message.
struct AppError: Identifiable { let id = UUID(); let title: String; let message: String } - 2
Hold it in optional state
Declare an @State optional. nil means no alert; a value means present.
@State private var activeError: AppError? - 3
Attach an item alert
Bind the optional to .alert(item:) and format the buttons and message from the unwrapped value.
.alert(item: $activeError) { err in Alert(title: Text(err.title), message: Text(err.message)) } - 4
Trigger from a catch
In your async work, assign activeError inside the catch block on the main actor.
do { try await upload() } catch { activeError = AppError(title: "Failed", message: error.localizedDescription) }
Frequently Asked Questions
Why does my SwiftUI .alert(isPresented:) show blank or not appear when I attach it inside a ForEach row?
How do I add more than two buttons to a SwiftUI alert now that Alert() is deprecated?
Can I put a TextField inside a SwiftUI alert, and from which iOS version?
Why does my SwiftUI destructive alert button appear in a different position than I wrote it in code?
What replaces .actionSheet in SwiftUI for showing a bottom action sheet?
Keep exploring
Build on a foundation that handles the edge cases
The Swift Kit is a $99 one-time SwiftUI boilerplate with Supabase auth, RevenueCat paywalls, multi-provider AI, and a design system — including a typed error-alert layer so you ship polished dialogs from day one.
Get The Swift Kit — $99One-time purchase · Lifetime updates · 14-day refund