TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: NavigationStack – Pop to root

Forums > SwiftUI

Hi HWS-Fans, here is my problem:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack() {
            Screen1()
        }
        .padding()
    }
}

struct Screen1: View {
    var body: some View {
        Text("Screen 1")
            .font(.title)
        NavigationLink("Weiter") {
            Screen2()
        }
    }
}

struct Screen2: View {
    var body: some View {
        Text("Screen 2")
            .font(.title)
        NavigationLink("Weiter") {
            Screen3()
        }
    }
}

struct Screen3: View {
    var body: some View {
        Text("Screen 3")
            .font(.title)
        Button("Back to root") {
            // but how?
        }
    }
}

How can I go back to Screen1 and reset the NavigationStack? Thanks for helping!

2      

If you watch Stewart Lynch video iOS 16 Navigation Stack - Back to Root and Deep Links. Remember that some changes to ObservableObject

3      

Hi! One way to solve this, well depending on what you need to do inside is like that. This is just one of the many options possible.

struct ContentView: View {
    // Here you monitor stack for views
    @State private var navPath: [String] = []

    var body: some View {
        NavigationStack(path: $navPath) {
            Screen1(path: $navPath)
        }
    }
}

struct Screen1: View {
    @Binding var path: [String]

    var body: some View {
        Text("Screen 1")
            .font(.title)
        NavigationLink(value: "View 2") {
            Text("Go to Screen 2")
        }
        .navigationDestination(for: String.self) { pathValue in
            // depending on the value you pass you will navigate accrodingly
            if pathValue == "View 2" {
                Screen2(path: $path)
            } else if pathValue == "View 3" {
                Screen3(path: $path)
            }
        }
    }
}

struct Screen2: View {
    @Binding var path: [String]
    var body: some View {
        Text("Screen 2")
            .font(.title)
        NavigationLink(value: "View 3") {
            Text("Go to Screen 3")
        }
    }
}

struct Screen3: View {
    @Binding var path: [String]
    var body: some View {
        Text("Screen 3")
            .font(.title)
        Button("Back to root") {
            // to navigate to root view you simply pop all the views from navPath
            path.removeAll()
        }
    }
}

3      

Yet another option using coordinator and enum for navigating, which I personally prefer, as more elegant way and coordination from one place. This one is using observable object so need import Observation framework.

import Observation

struct ContentView: View {
    @State private var coordinator = NavigationCoordinator()

    var body: some View {
        NavigationStack(path: $coordinator.paths) {
            // Initially show screen1
            coordinator.navigate(to: .screen1)
            // navigate depending on the screen added to paths property in the coordinator
                .navigationDestination(for: Screens.self) { screen in
                    coordinator.navigate(to: screen)
                }
        }
        // inject object into environment so there is no need to pass to each view
        .environment(coordinator)
    }
}

struct Screen1: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    var body: some View {
        VStack {
            Text("Screen 1")
                .font(.title)

            Button("Go to Screen 2") {
                coordinator.push(.screen2)
            }
        }
    }
}

struct Screen2: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    var body: some View {
        Text("Screen 2")
            .font(.title)
        Button("Go to Screen 3") {
            coordinator.push(.screen3)
        }
    }
}

struct Screen3: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    var body: some View {
        Text("Screen 3")
            .font(.title)
        Button("Back to root") {
            coordinator.popToRoot()
        }
    }
}

// Screens that we need to navigate
enum Screens {
    case screen1
    case screen2
    case screen3
}

// Object that will handle all the navigation
@Observable
class NavigationCoordinator {
    var paths = NavigationPath()

    @ViewBuilder
     func navigate(to screen: Screens) -> some View {
        switch screen {
        case .screen1:
            Screen1()
        case .screen2:
            Screen2()
        case .screen3:
            Screen3()
        }
    }

    // add screen
    func push(_ screen: Screens) {
        paths.append(screen)
    }

    // remove last screen
    func pop() {
        paths.removeLast()
    }

    // go to root screen
    func popToRoot() {
        paths.removeLast(paths.count)
    }
}

4      

Thank you all! The last one is quite sophisticated!

2      

A quetion to @ygeras about the coordinator you provided. Seems nice and decoupled but the question is how would you modify the "navigate" method to allow passing some dependencies to the screens? Because almost always you will have some object as a dependency for each screen so how would you achieve it?

2      

Hi there! Well currenly I can say there are several options to do that. All depends on what exactly you need to pass and how are the views interconnected i would say. Off the top of my head I can offer something like this:

import SwiftUI
import Observation

// Lets assume we need to pass this item
struct ItemToPass {
    var name: String
}

// As option we can create observable object
class UserData: Observable {
    let data = [
        ItemToPass(name: "Item for Screen 1"),
        ItemToPass(name: "Item for Screen 2"),
        ItemToPass(name: "Item for Screen 3")
    ]
}

struct ContentView: View {
    @State private var coordinator = NavigationCoordinator()
    let userData = UserData()

    var body: some View {
        NavigationStack(path: $coordinator.paths) {
            // Initially show screen1
            coordinator.navigate(to: .screen1, valueToPass: userData.data[0])
            // navigate depending on the screen added to paths property in the coordinator
                .navigationDestination(for: Screens.self) { screen in
                    coordinator.navigate(to: screen, valueToPass: userData.data[0])
                }
        }
        // inject object into environment so there is no need to pass to each view
        .environment(coordinator)
        // inject userData object to be accessible in any view
        .environment(userData)
    }
}

struct Screen1: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    @Environment(UserData.self) var userData: UserData

    var body: some View {
        VStack {
            Text("Screen 1")
                .font(.title)

            Text(userData.data[0].name)
                .font(.largeTitle)
                .foregroundStyle(.red)

            Button("Go to Screen 2") {
                coordinator.push(.screen2)
            }
        }
    }
}

struct Screen2: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    @Environment(UserData.self) var userData: UserData

    var body: some View {
        Text("Screen 2")
            .font(.title)

        Text(userData.data[1].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Go to Screen 3") {
            coordinator.push(.screen3)
        }
    }
}

struct Screen3: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    @Environment(UserData.self) var userData: UserData

    var body: some View {
        Text("Screen 3")
            .font(.title)

        Text(userData.data[2].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Back to root") {
            coordinator.popToRoot()
        }
    }
}

// Screens that we need to navigate
enum Screens {
    case screen1
    case screen2
    case screen3
}

// Object that will handle all the navigation
@Observable
class NavigationCoordinator {
    var paths = NavigationPath()

    // We will add this item to navigate method to pass
    @ViewBuilder
    func navigate(to screen: Screens, valueToPass: ItemToPass) -> some View {
        switch screen {
        case .screen1:
            Screen1()
        case .screen2:
            Screen2()
        case .screen3:
            Screen3()
        }
    }

    // add screen
    func push(_ screen: Screens) {
        paths.append(screen)
    }

    // remove last screen
    func pop() {
        paths.removeLast()
    }

    // go to root screen
    func popToRoot() {
        paths.removeLast(paths.count)
    }
}

PS. Actually in this example you don't need to pass the value in the method. The object will be accessible via @Environment. The proper way, to pass the data to the view is in the below post

2      

Another option is to inject the value into the view. Once again all depends on data you need to handle and pass. But there is a way to pass it around.

import SwiftUI
import Observation

// Lets assume we need to pass this item
struct ItemToPass {
    var name: String
}

struct ContentView: View {
    @State private var coordinator = NavigationCoordinator()

    let items = [
        ItemToPass(name: "Item for Screen 1"),
        ItemToPass(name: "Item for Screen 2"),
        ItemToPass(name: "Item for Screen 3")
    ]

    var body: some View {
        NavigationStack(path: $coordinator.paths) {
            // Initially show screen1
            coordinator.navigate(to: .screen1, valueToPass: items)
            // navigate depending on the screen added to paths property in the coordinator
                .navigationDestination(for: Screens.self) { screen in
                    coordinator.navigate(to: screen, valueToPass: items)
                }
        }
        // inject object into environment so there is no need to pass to each view
        .environment(coordinator)
    }
}

struct Screen1: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    let items: [ItemToPass]

    var body: some View {
        VStack {
            Text("Screen 1")
                .font(.title)

            Text(items[0].name)
                .font(.largeTitle)
                .foregroundStyle(.red)

            Button("Go to Screen 2") {
                coordinator.push(.screen2)
            }
        }
    }
}

struct Screen2: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    let items: [ItemToPass]

    var body: some View {
        Text("Screen 2")
            .font(.title)

        Text(items[1].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Go to Screen 3") {
            coordinator.push(.screen3)
        }
    }
}

struct Screen3: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator
    let items: [ItemToPass]

    var body: some View {
        Text("Screen 3")
            .font(.title)

        Text(items[2].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Back to root") {
            coordinator.popToRoot()
        }
    }
}

// Screens that we need to navigate
enum Screens {
    case screen1
    case screen2
    case screen3
}

// Object that will handle all the navigation
@Observable
class NavigationCoordinator {
    var paths = NavigationPath()

    // We will add this item to navigate method to pass
    @ViewBuilder
    func navigate(to screen: Screens, valueToPass: [ItemToPass]) -> some View {
        switch screen {
        case .screen1:
            Screen1(items: valueToPass)
        case .screen2:
            Screen2(items: valueToPass)
        case .screen3:
            Screen3(items: valueToPass)
        }
    }

    // add screen
    func push(_ screen: Screens) {
        paths.append(screen)
    }

    // remove last screen
    func pop() {
        paths.removeLast()
    }

    // go to root screen
    func popToRoot() {
        paths.removeLast(paths.count)
    }
}

2      

Yet another option that can be utilize I think is the associated value of enum structure. So hope those options will suffice :)

import SwiftUI
import Observation

// Lets assume we need to pass this item
struct ItemToPass: Hashable {
    var name: String
}

struct ContentView: View {
    @State private var coordinator = NavigationCoordinator()
    let items = [
        ItemToPass(name: "Item for Screen 1"),
        ItemToPass(name: "Item for Screen 2"),
        ItemToPass(name: "Item for Screen 3")
    ]

    var body: some View {
        NavigationStack(path: $coordinator.paths) {
            // Initially show screen1
            coordinator.navigate(to: .screen1(value: items))
            // navigate depending on the screen added to paths property in the coordinator
                .navigationDestination(for: Screens.self) { screen in
                    coordinator.navigate(to: screen)
                }
        }
        // inject object into environment so there is no need to pass to each view
        .environment(coordinator)
    }
}

struct Screen1: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    let items: [ItemToPass]

    var body: some View {
        VStack {
            Text("Screen 1")
                .font(.title)

            Text(items[0].name)
                .font(.largeTitle)
                .foregroundStyle(.red)

            Button("Go to Screen 2") {
                coordinator.push(.screen2(value: items))
            }
        }
    }
}

struct Screen2: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    let items: [ItemToPass]

    var body: some View {
        Text("Screen 2")
            .font(.title)

        Text(items[1].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Go to Screen 3") {
            coordinator.push(.screen3(value: items))
        }
    }
}

struct Screen3: View {
    // Access coordinator object in the environment
    @Environment(NavigationCoordinator.self) var coordinator: NavigationCoordinator

    let items: [ItemToPass]

    var body: some View {
        Text("Screen 3")
            .font(.title)

        Text(items[2].name)
            .font(.largeTitle)
            .foregroundStyle(.red)

        Button("Back to root") {
            coordinator.popToRoot()
        }
    }
}

// Screens that we need to navigate
enum Screens: Hashable {
    case screen1(value: [ItemToPass])
    case screen2(value: [ItemToPass])
    case screen3(value: [ItemToPass])
}

// Object that will handle all the navigation
@Observable
class NavigationCoordinator {
    var paths = NavigationPath()

    // We will add this item to navigate method to pass
    @ViewBuilder
    func navigate(to screen: Screens) -> some View {
        switch screen {
        case .screen1(let value):
            Screen1(items: value)
        case .screen2(let value):
            Screen2(items: value)
        case .screen3(let value):
            Screen3(items: value)
        }
    }

    // add screen
    func push(_ screen: Screens) {
        paths.append(screen)
    }

    // remove last screen
    func pop() {
        paths.removeLast()
    }

    // go to root screen
    func popToRoot() {
        paths.removeLast(paths.count)
    }
}

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.