Member-only story
How to Deal With Modal Views in SwiftUI
Everything you need to know about sheets
When presenting a small piece of extra information on the screen, showing a modal view is essential. With UIKit, we could do this with presentViewController:animated:completion:
function.
However, when using SwiftUI, we need to shift our thinking towards using view or environment state, as the modal view is now called a sheet.
Let’s check this out in detail.
Open Modal View (aka Sheet)
SwiftUI sheets help us show a modal view to users. sheet
is an instance method to the View Presentation. It describes how we can show our SwiftUI views, covering specific user journey scenarios.
Let’s say we want to display information about our app to users.
Firstly, we need to define whether the app should show a modal view or not, binding this with the Bool
value.
The keyword here is “should” because once we dismiss it, the presented view value is set back to false
. This value is decorated with an @State
property wrapper or could come from the ObservableObject
ViewModel. For simplicity’s sake, we’re not going to talk about ViewModels in this post.
Secondly, we need to change the view or, in some cases, the environment state. Once we are using the @State
property wrapper, we can just set it to true
and SwiftUI will do the rest to present the modal view.
Let’s look at how we can do it in the code:
When we run the app, we can now open the modal view and see the detailed information:
Close Modal View Programmatically
Our app users can simply slide the modal view down, and it will hide with a nice animation. Set the state to false
to hide…