Presenting new views using sheets
SwiftUI's sheets are used to present new views over existing ones while allowing the user to dismiss the new view by dragging it down.
In this recipe, we will learn how to present a sheet to the user and add navigation items to the sheet.
Getting ready
Create a new SwiftUI project named PresentingSheets
.
How to do it
We shall create two SwiftUI views named SheetView
and SheetWithNavView
that will be displayed modally when a button is clicked. The steps are as follows:
- In
ContentView.swift
, between thestruct
declaration and thebody
variable, add two state variables,showSheet
andsheetWithNav
. The state variables will be used to trigger the sheet presentation:@State private var showSheet = false @State private var sheetWithNav = false;
- Add a
VStack
and aButton
that changes the value of ourshowSheet
variable totrue
when clicked. Add a.sheet()
modifier to the button that gets displayed whenshowSheet
is set totrue...