Skip to content
DeveloperMemos

How to Show a Sheet in SwiftUI

SwiftUI, Sheet1 min read

In SwiftUI, a sheet is a view that appears in a modal dialog on top of the current view. The sheet view is presented when the user interacts with a button or any other user interface element that triggers an action. In this tutorial, we will learn how to show a sheet view in SwiftUI.

Adding a Button

To show a sheet view in SwiftUI, we first need to add a button to our user interface. Here's an example:

1struct ContentView: View {
2 @State private var isShowingSheet = false
3
4 var body: some View {
5 VStack {
6 Button("Show Sheet") {
7 isShowingSheet.toggle()
8 }
9 }
10 .sheet(isPresented: $isShowingSheet) {
11 SheetView()
12 }
13 }
14}
15
16struct SheetView: View {
17 var body: some View {
18 Text("Hello, World!")
19 }
20}

In this example, we added a button to our view, and we use the sheet modifier to present a sheet view when the user taps the button. The sheet modifier takes two arguments: the isPresented Boolean binding that controls whether the sheet view is visible or not, and the closure that returns the sheet view to present.

Passing Data to the Sheet View

We can also pass data to the sheet view by adding properties to the sheet view's initializer. Here's an example:

1struct ContentView: View {
2 @State private var isShowingSheet = false
3
4 var body: some View {
5 VStack {
6 Button("Show Sheet") {
7 isShowingSheet.toggle()
8 }
9 }
10 .sheet(isPresented: $isShowingSheet) {
11 SheetView(message: "Hello, World!")
12 }
13 }
14}
15
16struct SheetView: View {
17 let message: String
18
19 var body: some View {
20 Text(message)
21 }
22}

In this example, we added a message property to the SheetView struct and passed a value to it when we created the sheet view. We then used the message property to display a message in the sheet view.

Summary

  • To show a sheet view in SwiftUI, use the sheet modifier.
  • The sheet modifier takes two arguments: the isPresented Boolean binding that controls whether the sheet view is visible or not, and the closure that returns the sheet view to present.
  • We can pass data to the sheet view by adding properties to its initializer.