<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gleb on Medium]]></title>
        <description><![CDATA[Stories by Gleb on Medium]]></description>
        <link>https://medium.com/@glbus?source=rss-aa4eda726cd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9SePPZloGK5DUsme.jpg</url>
            <title>Stories by Gleb on Medium</title>
            <link>https://medium.com/@glbus?source=rss-aa4eda726cd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:17:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@glbus/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scalable SwiftUI Navigation. Part 2 — NavigationStack And TabView]]></title>
            <link>https://medium.com/@glbus/scalable-swiftui-navigation-part-2-navigationstack-and-tabview-6098bf45d550?source=rss-aa4eda726cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6098bf45d550</guid>
            <dc:creator><![CDATA[Gleb]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 17:35:27 GMT</pubDate>
            <atom:updated>2025-05-11T16:18:32.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable SwiftUI Navigation. Part 2 — NavigationStack And TabView</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svFUkkV01xgATLTR15rxvg.png" /></figure><h3>Intro</h3><p>In the <a href="https://medium.com/@glbus/scalable-swiftui-navigation-748db9aa594c">first part</a> of this series, we established a foundational navigation system in SwiftUI using a lightweight coordinator pattern. We focused on managing modal presentations and introduced a base router to handle navigation states.</p><h3><strong>Task</strong></h3><p>Now, let’s build a more complex example — something closer to a real-world app.</p><p>We’re going to create a <strong>tab bar app with two tabs</strong>.<br>Each tab will have its own navigation stack and will allow pushing to a second screen.</p><p>In addition:</p><ul><li>We’ll add an <strong>“Add Entity”</strong> button that presents a modal flow with its own independent navigation stack.</li><li>We’ll also add a button to present <strong>helper modal screens</strong>.</li></ul><p>This example will show how flexible and reusable our router system is, even when managing multiple navigation contexts at the same time.</p><h3>Code</h3><p>Let’s start by creating a <strong>StackRouter</strong>.</p><p>StackRouter is responsible for handling push and pop navigation inside a single NavigationStack.<br>It extends our BaseRouter and manages its own stack of destinations.</p><pre>class StackRouter: BaseRouter {<br>    @Published var paths: [StackDestination] = []<br><br>    func push(_ destination: StackDestination) {<br>        paths.append(destination)<br>    }<br><br>    func pop() {<br>        if !paths.isEmpty {<br>            paths.removeLast()<br>        }<br>    }<br>}</pre><p>Next, let’s create a <strong>TabRouter</strong>.</p><p>TabRouter is responsible for managing the selected tab and providing a separate StackRouter for each tab.<br>This way, each tab gets its own independent NavigationStack and its own navigation history.</p><pre>class TabRouter: BaseRouter {<br>    @Published var selectedTab: Tab = .tab1<br>    @Published var routers: [Tab: StackRouter]<br><br>    subscript(tab: Tab) -&gt; StackRouter {<br>        get { routers[tab, default: StackRouter()] }<br>        set { routers[tab] = newValue }<br>    }<br><br>    override init() {<br>        self.routers = Dictionary(uniqueKeysWithValues: Tab.allCases.map { ($0, StackRouter()) })<br>    }<br>}</pre><p>Great, now we have our <strong>“view models” for navigation</strong> ready.<br>Let’s connect them to our views and see how everything comes together.</p><p>Now, let’s connect the StackRouter to a NavigationStack using a view modifier.</p><pre>struct AppStackRouter: ViewModifier {<br>    let router: BaseRouter<br>    @ObservedObject var stackRouter: StackRouter<br><br>    func body(content: Content) -&gt; some View {<br>        NavigationStack(path: $stackRouter.paths) {<br>            content<br>                .navigationDestination(for: StackDestination.self) { destination in<br>                    switch destination {<br>                    case .stack2:<br>                        Stack2(router: router)<br>                    case .tabStack2:<br>                        if let tabRouter = router as? TabRouter {<br>                            TabStack2(router: tabRouter, stackRouter: stackRouter)<br>                        }<br>                    }<br>                }<br>        }<br>    }<br>}</pre><p>Now, let’s build the <strong>TabRootView</strong> that connects the TabRouter to the TabView.</p><pre>struct TabRootView: View {<br>    @ObservedObject var router: TabRouter<br><br>    var body: some View {<br>        TabView(selection: $router.selectedTab) {<br>            ForEach(Tab.allCases, id: \.rawValue) { tab in<br>                TabStack1(router: router, stackRouter: router[tab])<br>                    .withStackRootView(router: router, stackRouter: router[tab])<br>                    .tabItem {<br>                        Image(systemName: tab.icon)<br>                        Text(tab.title)<br>                    }<br>                    .tag(tab)<br>            }<br>        }<br>    }<br>}</pre><p>Each tab:</p><ul><li>Creates its own independent NavigationStack through withStackRootView().</li><li>Shares the same TabRouter for tab selection, but <strong>uses a separate </strong><strong>StackRouter</strong> for its own stack navigation.</li><li>Displays its icon and title using the Tab enum.</li></ul><p>This structure makes sure that each tab can navigate independently without interfering with other tabs’ navigation history.</p><p>Let’s update AppBaseRouter based on what we built in <a href="https://medium.com/@glbus/scalable-swiftui-navigation-748db9aa594c">Part 1</a>.</p><p>Now, it should handle not just simple sheets, but also sheets that need their own navigation stacks.</p><p>Here’s the updated code:</p><pre>struct AppBaseRouter: ViewModifier {<br>    @ObservedObject var router: BaseRouter<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .sheet(item: $router.sheetDestination) { destination in<br>                switch destination {<br>                case .sheet1:<br>                    if let childRouter = router.childRouter {<br>                        Sheet1(router: childRouter)<br>                            .withAppBaseRouter(childRouter)<br>                    }<br>                case .stack1:<br>                    if let childRouter = router.childRouter as? StackRouter {<br>                        Stack1(router: childRouter, stackRouter: childRouter)<br>                            .withStackRootView(router: childRouter, stackRouter: childRouter)<br>                            .withAppBaseRouter(childRouter)<br>                    }<br>                }<br>            }<br>    }<br>}</pre><p>This implementation uses core concepts we discussed in <a href="https://medium.com/@glbus/scalable-swiftui-navigation-748db9aa594c">Part 1</a>:</p><p><strong>Child Routers</strong></p><ul><li>When presenting a new sheet, we create a new instance of a router (child router).</li><li>This keeps each presented flow completely independent and allows us to manage navigation inside modals cleanly.</li></ul><p><strong>Router Injection Across Navigation Contexts</strong></p><p>Each presented screen receives its router instance explicitly through initializer injection. This gives us full control over navigation flows and avoids relying on implicit state sharing.</p><p>In cases like .stack1, we may need to pass the same router instance in multiple roles — for example, once as a StackRouter (to handle stack navigation) and once as a BaseRouter (to manage sheet presentations within that flow).</p><p>This works because StackRouter is a subclass of BaseRouter, and passing it under both types allows different layers of the view hierarchy to access the functionality they need — without type casting or relying on global state.</p><p><strong>In short:</strong></p><blockquote><em>We pass the same router instance in multiple roles to satisfy different parts of the navigation system — one for stack-based navigation, and another for modal coordination — while keeping dependencies fully explicit and predictable.</em></blockquote><h3><strong>Demo</strong></h3><p>Let’s quickly test everything we’ve built so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ttfk2WVAxuOmNgHexuNztA.gif" /></figure><p>You can find the full source code for this example here (folder Part2):<br>👉 <a href="https://github.com/glebus/graphrouter/tree/main/Part2">GraphRouter GitHub Repository</a></p><p>Feel free to explore it, test it, and use it as a starting point for your own projects.</p><p>In the next part, we’ll extend the system to handle <strong>global states</strong> like presenting an authentication screen automatically on a 401 response and handling <strong>deep links</strong> — all without breaking the flexible router setup we have built so far.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6098bf45d550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable SwiftUI Navigation. Part 1]]></title>
            <link>https://medium.com/@glbus/scalable-swiftui-navigation-748db9aa594c?source=rss-aa4eda726cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/748db9aa594c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[coordinator-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation-stack]]></category>
            <dc:creator><![CDATA[Gleb]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 16:05:39 GMT</pubDate>
            <atom:updated>2025-05-30T13:36:58.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIFC-XRI5Ol9XVf6QyK8LA.png" /></figure><h3>Intro</h3><p>Navigation is the backbone of any app and something developers need to consider carefully from the very beginning of a project. Unfortunately, Apple doesn’t provide a clear, structured approach for handling navigation in complex SwiftUI apps. Most of their examples are basic and do not cover real-world scenarios. This leaves room for interpretation and has led to the rise of many third-party libraries that try to solve the challenges of SwiftUI navigation in a more scalable way.</p><h3>Requirements</h3><p>It’s difficult to create a single set of navigation requirements that fits every app. Some apps are quite simple and only need a basic setup using NavigationStack and NavigationLink. Others, on the other hand, require fully custom navigation systems with complex animations, which demand a completely different approach.</p><p>In this article, we’ll focus on the most common and practical use cases, not the extreme edge cases.</p><p>For a typical app, a good navigation system should have:</p><ul><li><strong>Centralized control</strong>: Navigation should be described and controlled from a central place in the app. (For example, in VIPER architecture, navigation is often spread across multiple Routers, making it harder to understand and maintain)</li><li><strong>Flexibility</strong>: The system should support different types of transitions, including push stacks, modal presentations, and tab bar navigation.</li><li><strong>Programmatic navigation</strong>: It should be possible to trigger navigation based on app logic, not only user interactions.</li><li><strong>Deep link support</strong>: The app should be able to open specific screens directly from URLs, notifications, or external events.</li><li><strong>State-driven navigation</strong>: Navigation should be driven by app state, making it predictable, testable, and easier to restore when needed.</li></ul><p>By keeping these requirements in mind, we can design a navigation system that is simple enough for small projects but also scalable for larger apps.</p><h3>Solution</h3><p>Before iOS 16, SwiftUI didn’t provide the necessary tools to build an independent and flexible navigation system that could cover real-world requirements. The community tried to solve this problem using different complex solutions based on NavigationLink, but overall, I would recommend using a UIKit-based navigation system for any project that needs to support iOS versions below 16.</p><p>While working on my apps (WorkoutHub, CountKit, Animols, IkigAI, and SuperDice), I found a practical solution that I would like to share. This approach is inspired by <a href="https://medium.com/u/b067c9115d59">Thomas Ricouard</a>’s open-source project <a href="https://github.com/Dimillian/IcySky"><strong>IcySky</strong></a>, as well as the excellent <a href="https://www.youtube.com/@technecoding">Techne Coding</a> series on <a href="https://www.youtube.com/watch?v=dZ9GQhFH1fY"><em>Advanced SwiftUI with UIKit Coordinator Navigation</em></a>.</p><h4>Pattern Coordinator</h4><p>The Coordinator pattern is quite popular in the UIKit world for managing navigation systems. In simple terms, it splits the app’s navigation into several flow- or module-related coordinators. Each coordinator defines its own entry point, encapsulates the navigation logic, and manages connections between different flows.</p><p>Using coordinators helps to:</p><ul><li>Keep navigation logic separate from views.</li><li>Make flows modular and easier to test.</li><li>Connect different parts of the app cleanly.</li></ul><p>Let’s see how we can apply this idea to SwiftUI.</p><h4>SwiftUI</h4><p>SwiftUI provides several built-in ways to navigate between screens. I like to think of them based on the <strong>presentation context</strong>.</p><ul><li><strong>TabBar / NavigationStack</strong>:<br>When using a TabView or NavigationStack, the screens pushed onto the stack stay within the same presentation context. In simple words, the TabView or NavigationStack just wraps and manages the screens inside it.</li><li><strong>.fullScreenCover / .sheet</strong>:<br>On the other hand, when presenting a screen using .fullScreenCover or .sheet, SwiftUI creates a <strong>new presentation context</strong>. In these cases, if we want to push additional screens inside the presented view, we must provide a new NavigationStack.</li></ul><p>Because of this difference, we’ll start by solving the navigation for modal presentations (.sheet, .fullScreenCover) first, and then extend the solution to cover stack-based navigation (NavigationStack, TabView) inside a single context.</p><h4>Code</h4><p>Let’s start by defining <strong>Router</strong> that will cover .sheet presentations first.</p><pre>enum SheetDestination {<br>    case sheet1<br>}<br><br>extension SheetDestination: Identifiable {<br>    public var id: Self { self }<br>}</pre><p>We need to conform to the Identifiable protocol because .sheet in SwiftUI require an identifiable item to present.</p><p>Now, let’s create a <strong>BaseRouter</strong> that will handle the state for our sheet destinations:</p><pre>class BaseRouter: ObservableObject {<br>    @Published var sheetDestination: SheetDestination?<br><br>    func presentSheet(_ destination: SheetDestination, router: BaseRouter? = BaseRouter()) {<br>        sheetDestination = destination<br>    }<br>}</pre><p>Basically, this acts as a <strong>view model for our navigation</strong>.<br>We use ObservableObject and @Published to support SwiftUI’s reactive system (starting from iOS 16).</p><p>Next, let’s create some <strong>stub screens</strong> to display:</p><pre>struct RootView: View {<br>    @ObservedObject var router: BaseRouter<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;RootView&quot;)<br>            Spacer()<br>            Button (action: {<br>                router.presentSheet(.sheet1)<br>            }, label: {<br>                Text(&quot;Open Sheet1&quot;)<br>            })<br>            .buttonStyle(.borderedProminent)<br>            Spacer()<br>        }<br>        .padding()<br>    }<br>}</pre><pre>struct Sheet1: View {<br>    @ObservedObject var router: BaseRouter<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Sheet1&quot;)<br>            Spacer()<br>            Button (action: {<br>                router.sheetDestination = nil<br>            }, label: {<br>                Text(&quot;Close Sheet1&quot;)<br>            })<br>            .buttonStyle(.borderedProminent)<br>            Spacer()<br>        }<br>        .padding()<br>    }<br>}</pre><p>Here, we are injecting the router into the views. Now, let’s connect our views to the router using a custom <strong>ViewModifier</strong>:</p><pre>struct AppBaseRouter: ViewModifier {<br>    @ObservedObject var router: BaseRouter<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .sheet(item: $router.sheetDestination) { destination in<br>                switch destination {<br>                case .sheet1:<br>                    Sheet1(router: router)<br>                }<br>            }<br>    }<br>}<br><br>extension View {<br>    public func withBaseAppRouter(_ router: BaseRouter) -&gt; some View {<br>        modifier(AppBaseRouter(router: router))<br>    }<br>}</pre><p>We created a <strong>view modifier</strong> withBaseAppRouter() that listens to changes in BaseRouter and presents the correct sheet when needed.</p><p>The result is very promising and gives a strong foundation for more advanced navigation flows!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2ldmD2Cn7n5Q2EJD_Io93g.gif" /></figure><p>However, if we want to <strong>present another sheet on top of an already presented sheet</strong>, the current setup will not work.<br>SwiftUI allows only one .sheet per view hierarchy, so to handle <strong>nested sheets</strong>, we need to <strong>provide a separate instance of </strong><strong>BaseRouter</strong>.</p><p>Let’s improve the solution by update the BaseRouter to store a child router</p><pre>class BaseRouter: ObservableObject {<br>    @Published var sheetDestination: SheetDestination?<br><br>    var childRouter: BaseRouter?<br><br>    func presentSheet(_ destination: SheetDestination, router: BaseRouter? = BaseRouter()) {<br>        childRouter = router<br>        sheetDestination = destination<br>    }<br>}</pre><pre>struct AppBaseRouter: ViewModifier {<br>    @ObservedObject var router: BaseRouter<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .sheet(item: $router.sheetDestination) { destination in<br>                switch destination {<br>                case .sheet1:<br>                    if let childRouter = router.childRouter {<br>                        Sheet1(router: router)<br>                            .withBaseAppRouter(router)<br>                    }<br>                }<br>            }<br>    }<br><br>    // ...<br>}</pre><p>Now, we can easily <strong>open a new sheet from within another sheet</strong> using the same BaseRouter class, without adding any special logic inside the views themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DsO3l5JnbAEyU_s2SihY7Q.gif" /></figure><p>This multi-sheet setup is not something you would often use in a real-life app, but it demonstrates the <strong>flexibility</strong> and <strong>control</strong> you gain by managing navigation manually.</p><p>Now let’s extend the router to add the ability to <strong>close all sheets and return to the root</strong> from any screen.</p><p>We update the BaseRouter to keep a <strong>reference to the parent router</strong>:</p><pre>class BaseRouter: ObservableObject {<br>    @Published var sheetDestination: SheetDestination?<br><br>    weak var parentRouter: BaseRouter?<br>    var childRouter: BaseRouter?<br><br>    func presentSheet(_ destination: SheetDestination, router: BaseRouter? = BaseRouter()) {<br>        childRouter = router<br>        childRouter?.parentRouter = self<br>        sheetDestination = destination<br>    }<br><br>    func close() {<br>        sheetDestination = nil<br>        parentRouter?.sheetDestination = nil<br>        parentRouter?.childRouter = nil<br>    }<br><br>    func closeToRoot() {<br>        if let parentRouter {<br>            parentRouter.closeToRoot()<br>        } else {<br>            sheetDestination = nil<br>        }<br>    }<br>}</pre><p>By keeping a reference to the parent router, we can <strong>easily navigate back to the root</strong> from <strong>any deeply presented sheet </strong>without manually dismissing each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gY9q2RsfxdTB_uUqftkgKg.gif" /></figure><p>You can find the full source code for this example here:<br>👉 <a href="https://github.com/glebus/graphrouter">GraphRouter GitHub Repository</a></p><p>Feel free to explore it, test it, and use it as a starting point for your own projects.</p><p>In the next part, we’ll extend the system to handle <strong>NavigationStack pushes </strong>allowing us to manage standard push-style navigation alongside modals using the same flexible router setup.</p><p>P.S. <a href="https://medium.com/@glbus/scalable-swiftui-navigation-part-2-navigationstack-and-tabview-6098bf45d550">Next Part</a> is out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=748db9aa594c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>