How to Use Sheet in SwiftUI: Simple Guide with Examples
In SwiftUI, you use the
sheet modifier to present a modal view. It requires a binding Boolean to control its visibility and a closure that returns the content view to show. This lets you easily display temporary screens over your current view.Syntax
The sheet modifier attaches to a view and takes two main parts: a binding Boolean that controls when the sheet appears, and a closure that returns the view to display inside the sheet.
Example parts:
isPresented: $showSheet- a binding to a Boolean state that shows or hides the sheet.content: { YourSheetView() }- a closure returning the sheet's content view.
swift
someView.sheet(isPresented: $showSheet) {
YourSheetView()
}Output
No visible output until $showSheet becomes true, then YourSheetView appears modally.
Example
This example shows a button that toggles a sheet. When the button is tapped, the sheet appears with a simple text and a dismiss button.
swift
import SwiftUI struct ContentView: View { @State private var showSheet = false var body: some View { Button("Show Sheet") { showSheet = true } .sheet(isPresented: $showSheet) { VStack { Text("Hello from the sheet!") .font(.title) .padding() Button("Dismiss") { showSheet = false } .padding() } } } }
Output
A button labeled "Show Sheet" is visible. Tapping it opens a modal sheet with "Hello from the sheet!" text and a "Dismiss" button that closes the sheet.
Common Pitfalls
Common mistakes when using sheet include:
- Not using a
@Stateor@BindingBoolean to control the sheet, causing it not to appear. - Forgetting to update the Boolean to
falseto dismiss the sheet. - Trying to present multiple sheets at once without managing state properly.
Always ensure the Boolean state is properly connected and updated.
swift
/* Wrong way: Using a constant true value - sheet never dismisses */ someView.sheet(isPresented: .constant(true)) { Text("Sheet") } /* Right way: Use @State and toggle it */ @State private var showSheet = false someView.sheet(isPresented: $showSheet) { Text("Sheet") }
Output
Wrong way: Sheet appears but cannot be dismissed by changing state.
Right way: Sheet appears and can be dismissed by toggling showSheet to false.
Quick Reference
Tips for using sheet in SwiftUI:
- Use
@Stateor@BindingBoolean to control visibility. - The sheet content is a closure returning a view.
- Dismiss the sheet by setting the Boolean to
false. - Sheets are modal and cover the current view.
- Use
onDismissparameter to run code when the sheet closes.
Key Takeaways
Use the sheet modifier with a binding Boolean to present modal views in SwiftUI.
The sheet content is provided as a closure returning the view to display.
Control sheet visibility by toggling the Boolean state between true and false.
Always use @State or @Binding for the Boolean controlling the sheet.
Use the onDismiss parameter to handle actions after the sheet closes.