0
0
Ios-swiftHow-ToBeginner ยท 3 min read

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 Bool that shows the alert when true.
  • content closure: Returns an Alert describing 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 @State or @Binding variable to control alert visibility.
  • Forgetting to set the binding to true to show the alert.
  • Trying to show multiple alerts at once without managing state properly.
  • Using alert outside 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 a Bool to show/hide alert.
  • Alert(title:message:dismissButton:) creates a simple alert.
  • Use .default, .cancel, or .destructive buttons.
  • Use Identifiable data 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.