In this post, we will cover how to present and dismiss a modal view.
Find the source code at this Github Repo.
NOTE: this tutorial is using Xcode 11 and has been tested using iOS 13.1.2.
Let’s get started by making a new project using SwiftUI. When creating a new project, make sure that the language is set to Swift, and the User Interface is configured to SwiftUI like in the picture below.
show_modal
variableNow that the project is made, we need to open the ContentView.swift
file to declare a variable that determines whether or not to present the modal.
The variable has to be a binding variable and one that can update the view when changing, which is why we declare it as a State variable.
Let’s change the Text()
to a Button()
that sets show_modal
to true
.
I added a print()
statement to make sure the button works.
Go ahead and run the app (Command + R) and click on the button. By clicking on the button, “Button Pushed” will be printed in the console.
Now, let’s create the modal view. Create a new file and change the Text to “This is a Modal.” It should look like the code snippet below.
It’s time to make the modal appear from the button push on the first view. Open ContentView.swift
and add the following to the button.
What does .sheet() // more code
do? It is deciding if ModalView
should be presented when show_modal
changes.
.sheet(isPresented: Binding<Bool>){ /* View to present */}
is a modifier that can present the view when isPresented
is true
. In our example, show_modal
is a Binding<Bool>
because it is declared with @State
. We also set the view to be presented as ModalView()
.
ContentView.swift
should now be complete and look like this.
Running the application right now, we can dismiss the modal by dragging down from the top of the modal.
Dragging works to dismiss, but sometimes users would instead hit a button, or maybe you want the user to hit the button to confirm, and a drag cancels the operation. To add a button to dismiss the modal, we need to put add an Environment variable for presentationMode
and then call presentationMode.wrappedValue.dismiss()
. Here is how it looks in ModalView.swift
.
I’m going to break down what we did.
self.presentaionMode.wrappedValue.dismiss()
is the method that dismisses the Modal.Now, running the application, we can dismiss the view either by dragging or by tapping on the button.
I was asked by @cwhooten how to make a list that presents a dynamic modal. You can find that answer as a branch to the original example by clicking on this sentence.
Updated the note at the top.
Updated the note at the top since it has been tested with Release Xcode and Release iOS 13.
or support my work monthly on Patreon.
Supporting me on Ko-Fi, Buy Me a Coffee, or on Patreon will have your name listed as a supporter at the end of my streams for that month and on my supporters page.