Decoupling Navigation in SwiftUI

Marcel Kulina
5 min readMar 14, 2022

How to move your Navigation Flow away from your View Code

SwiftUI is a great way to build modern, interactive UIs. While it lacks some features that still need to be wrapped via UIKit, it is mature enough to be used in production for a good while now. But one thing that is still cumbersome to do is navigation — explicitly making the View irresponsible for navigation. This article will show a simple way to decouple your navigation from view logic. No UIKit required.

Ideal flow. Views only have loose coupling to each other.

NavigationLink

NavigationLinks are the primary source of navigation in SwiftUI. While they offer a simple yet elegant way to handle navigation in our apps, they can become quite limiting when navigation flow gets more complex.

Let’s look at the most simple NavigationLink for now.

A simple NavigationLink.

When the user taps on the content passed via label the link is triggered, and the NavigationView pushes destionation onto the View Stack. While this is fine for some cases, it already shows one big drawback: We cannot control when we want to navigate; the link is triggered immediately on tap. Another disadvantage is that we can only pop the new View when interacting with…

--

--

Responses (2)