Presenting Views with Sheets

Learn how to present a new view modally in SwiftUI using the .sheet modifier, triggered by a button and controlled by a @State variable.

Presenting Views with Sheets

Note:

This tutorial explains how to present views modally (as sheets) in response to user actions, like tapping a button.

Overview

In SwiftUI, there are different ways to navigate to another view. One way is to use a NavigationView, which pushes a new view onto a stack. Another common way is to present a view modally, as a "sheet" that slides up from the bottom of the screen. This is often used for tasks that are separate from the main user flow, like composing a new message or showing settings.

We can achieve this by using the .sheet modifier on a view, which is controlled by a Boolean state variable.

Reference:

Using the .sheet Modifier

The .sheet modifier takes a binding to a Boolean value. When this value is true, the sheet is presented. When it's false, the sheet is dismissed. To provide this binding, we use a property wrapper called @State.

The Code

  1. @State Variable: We create a @State variable (e.g., showingSheet) and initialize it to false. This variable will control whether the sheet is visible.
  2. Button Action: We create a Button. In its action closure, we toggle the state variable to true.
  3. .sheet Modifier: We attach the .sheet modifier to our button (or any view inside the body). We bind it to our state variable using the $ prefix. Inside the sheet's content closure, we provide the view that we want to present.
import SwiftUI

struct ContentView: View {
    // 1. A state variable to control the sheet's presentation
    @State private var showingSheet = false

    var body: some View {
        // 2. A button to trigger the sheet
        Button("Show Sheet") {
            // 3. Toggle the state variable to present the sheet
            self.showingSheet = true
        }
        .font(.largeTitle)
        // 4. The .sheet modifier
        .sheet(isPresented: $showingSheet) {
            // 5. The content to show in the sheet
            SecondView()
        }
    }
}

struct SecondView: View {
    // This allows the sheet to be dismissed from within
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
            Text("This is the sheet view!")
                .font(.title)
            Button("Dismiss") {
                presentationMode.wrappedValue.dismiss()
            }
            .padding()
        }
    }
}
Code for presenting a sheet

Note:

Presenting a view as a sheet is a common pattern for tasks that are modal or require focused user input without losing the context of the underlying view.