How do you present the standard iOS modal view with SwiftUI?
SwiftUI is a new framework that makes app development lightning fast. It was introduced by Apple this June at WWDC 2019.
I’m pretty sure this will be changed in the newer versions of the SwiftUI, but for now, here is an open-source package for everyone to present modal views conveniently. The library can be added as a Swift package to a project and benefit from updates, or just copy the file if the functionality covers all the edge cases for your project already.
Step 1: Add the ModalView Library as a Swift Package in Xcode
Here is the link: https://github.com/diniska/modal-view
In the library, we use an analogy with the existing navigation API:
ModalPresenteris similar toNavigationViewModalLinkis an analogue ofNavigationLink
Thus, the modal API will be familiar to everyone who has already dealt with navigation.
Step 2: Create ModalPresenter similarly to NavigationView
Let’s add ModalPresenter somewhere close to the root of our view.
It doesn’t have to be the root — just make sure it’s not inside a List, Form, or a similar view that creates subviews dynamically.
Step 3: Add ModalLink similarly to NavigationLink
We are wrapping Text that wants to trigger the modal view with NavigationLink.
Here you go:
In complex hierarchies, like navigation view with a form with buttons inside, is the place where ModalPresenter view shines comparing to the default API.
To put it short, that is pretty convenient. Now let’s check how we would implement that without the library and see what hidden results for List and Form views it will give us.
How Would You Display a Modal View Without Using the ModalView Library?
The default method is to use the sheet API. A sheet requires a binding to a Boolean which controls whether the dialogue is shown or hidden.
Also, don’t forget about toggling the state on button tap. In a simple case, the result would look like this.
Pretty good, huh? The hard part is in the list of items. Let’s try that:
You’ve probably got the idea.
The code is longer and less safe, as it is easy to write isPresented5 in one place and isPresented6 in the other just because of copy-pasting.
This is not a big issue, though. A big issue is that every button here works only once. Don’t ask me why.
To conclude, personally, I’ll go with the new ModalView library in my projects for now as this framework provides a bit simpler API and makes the code-writing experience even faster.
If you are aware of other edge cases, pull requests and issues are welcome in the package repo.
Enjoy your SwiftUI experience — the world can’t wait to see your new apps.
If you found this article beneficial, please consider following my Medium blog. It costs nothing for you but is immensely rewarding for me, as it helps me continue to share valuable content with readers like you. Thank you for your support!

