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.
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
@StateVariable: We create a@Statevariable (e.g.,showingSheet) and initialize it tofalse. This variable will control whether the sheet is visible.- Button Action: We create a
Button. In itsactionclosure, we toggle the state variable totrue. - .sheet Modifier: We attach the
.sheetmodifier 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()
}
}
}
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.