How to Use Alert in SwiftUI: Simple Guide with Examples
In SwiftUI, you use the
alert modifier on a view to show an alert. You bind it to a Bool or an Identifiable item that controls when the alert appears and define the alert content inside a closure.Syntax
The alert modifier attaches to a view and takes a binding to a Bool or an Identifiable item to control its visibility. Inside the closure, you create an Alert with a title, message, and buttons.
Example parts:
- isPresented: A binding to a
Boolthat shows the alert when true. - content closure: Returns an
Alertdescribing the alert's title, message, and buttons.
swift
alert(isPresented: $showAlert) {
Alert(
title: Text("Title"),
message: Text("Message"),
dismissButton: .default(Text("OK"))
)
}Output
Shows an alert with a title, message, and an OK button when showAlert is true.
Example
This example shows a button that toggles an alert when tapped. The alert has a title, message, and a single OK button to dismiss it.
swift
import SwiftUI struct ContentView: View { @State private var showAlert = false var body: some View { Button("Show Alert") { showAlert = true } .alert(isPresented: $showAlert) { Alert( title: Text("Hello SwiftUI"), message: Text("This is an alert example."), dismissButton: .default(Text("OK")) ) } } }
Output
A button labeled "Show Alert" that, when tapped, displays an alert with the title "Hello SwiftUI", message "This is an alert example.", and an OK button to close it.
Common Pitfalls
Common mistakes include:
- Not using a
@Stateor@Bindingvariable to control alert visibility. - Forgetting to set the binding to
trueto show the alert. - Trying to show multiple alerts at once without managing state properly.
- Using
alertoutside of a view modifier chain.
swift
/* Wrong: Alert without binding - won't show */ // alert(isPresented: .constant(false)) { ... } // Always false, alert never appears /* Right: Use @State to toggle alert */ @State private var showAlert = false // Then toggle showAlert = true to show alert
Quick Reference
Alert Modifier Cheat Sheet:
isPresented:Bind to aBoolto show/hide alert.Alert(title:message:dismissButton:)creates a simple alert.- Use
.default,.cancel, or.destructivebuttons. - Use
Identifiabledata for alerts with multiple options.
Key Takeaways
Use the alert modifier with a binding to control alert visibility in SwiftUI.
Define alert content with title, message, and buttons inside the alert closure.
Always use @State or @Binding variables to toggle alerts on and off.
Avoid showing multiple alerts simultaneously without managing state carefully.
Use .default, .cancel, and .destructive buttons to customize alert actions.