[SwiftUI] Manage Custom Dialog

Yoki
3 min readMay 25, 2021
Photo by Volodymyr Hryshchenko on Unsplash

Goal

  • Create a custom View and display it as a dialog
  • Make it possible to display multiple dialogs

Background

In SwiftUI, you can display standard alerts by using Alert. However, there are times when you want to display your own View as a dialog, as you did when you were developing with UIKit. Also, you may want to display multiple patterns of dialogs on a single screen. This article introduces something that satisfies such requirements.

Demo

The following is what we will create.

The entire code is at the end for your reference.

Content Pattern

First, create a custom dialog view. This is a part that inherits from View.

Then, create an Enum that summarizes them. This way, you can see the list of cases in your app that use custom dialogs, and you can easily replace the View in a specific case.

(The naming of case is contentDetail01, but I think more detailed naming would be better in practice. For simplicity's sake, I've done so.)

Manage Dialog Presentation

Next, we will create a class that controls the display of the dialog.

The role of this class is as follows

  • Update the display flag
  • Set the content to be displayed

From the View that displays the dialog, use the show method to display any content.

Custom Dialog Modifier

Display a custom dialog via a ViewModifier. This is based on this article: Custom View Dialog in SwiftUI | Swift UI recipes.

The main points are as follows.

  • Display a custom dialog on top of the original content in ViewModifiew.
  • Make the UI look like a dialog by placing a transparent black color that covers the entire screen.

Set Up

Now the elements are ready. Let’s try to show the dialog with View.

The View holds the DialogPresentation.

Display the dialog as follows.

dialogPresentataion.show(
content: .contentDetail01(isPresented: $dialogPresentataion.isPresented))

The flag is updated when the close button is pressed on the dialog side, so isPresented is passed.

Summary

Here is the entire code.

By creating a management class with the responsibility of displaying the dialog, we were able to hide the process of displaying the dialog and also support multiple display patterns.

If you have any suggestions or problems, please feel free to comment.

References

--

--