How to show a view on Top Layer with SwiftUI

How to show a view on Top Layer with SwiftUI

Sometimes our apps require to display a UI (like Progress Loader, Alert View, Toast UI or some other UI) on top of what's on screen.

Generic View could be the best solution for the same, Its visibility could be controlled purely depending on the need of app flow.

However, Sometimes new View appears behind the sheets or bottom sheets or fullScreenCover. This is just an edge case ( or limitation ) of a generic View showing on the top of other UIs.

In this article, let's discuss how we can solve this challenge and much more.

App UI hierarchy

Everything As we see on apps is placed on top of UIWindows. A window delivers touch events or actions to the correct views and responds to other events such as (device) orientation changes (like Landscape to Portrait or vice versa).

With the introduction of multiple Windows support for iPad (and Catalyst), UIWindows are associated with and managed by UIScenes, which represents a UI instance of our app.

Most of the time, We don't require any interaction with either of them, especially with SwiftUI's new life cycle. However, even on SwiftUI apps, those generic components are always preferred to set up and use very quickly with minimal code whenever the need arises.

Lastly, we always prefer to implement UISceneDelegate/UIWindowSceneDelegate to respond to various events related to the app's UIScene (and associated UISceneSession).

While a UIScene is normally set up with one window, scenes support multiple windows.

How to add extra windows to an app

Scenes do manage UIWindows, but we own the window life-cycle: if only the scene holds a reference to the window, the window will be de-allocated (and its UI won't show in the app).

Since we get our app's UIWindowScene instances via our UISceneDelegate / UIWindowSceneDelegate, adding windows there is probably the easiest way to do so.

Corresponding to the discussed changes, we need to modify SceneDelegate and add Alert View, Progress View or Toast View accordingly with Generic behaviour.

Please explore the code of the GitHub project (ShowViewOnTopLayerWithSwiftUI) to get more depth with discussed implementation.