Menu
Coddy logo textTech

Sheets And Alerts

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 37 of 50.

A sheet slides a view up over the current screen. It is shown while a Bool state is true:

@State private var showHelp = false

Button("Help") { showHelp = true }
    .sheet(isPresented: $showHelp) {
        Text("Swipe down to close")
    }

An alert asks a short question. It works the same way, with a title, buttons and an optional message:

Button("Delete") { askDelete = true }
    .alert("Delete photo?", isPresented: $askDelete) {
        Button("Delete", role: .destructive) { deletePhoto() }
        Button("Cancel", role: .cancel) { }
    } message: {
        Text("This cannot be undone.")
    }

Tapping any of the alert's buttons runs its action and closes the alert, setting the state back to false. Inside a sheet, @Environment(\.dismiss) var dismiss gives a dismiss() action that closes it from code.

challenge icon

Challenge

Medium

When the user taps Save, show an alert titled Saved! with the message Your note is stored. and one OK button. Use the showSaved state.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground