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.
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 = false3 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.
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 = false3 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: String18 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.
sheet
modifier.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.