SwiftUIX / Coordinator

A declarative navigation API for SwiftUI.
MIT License
252 stars 20 forks source link

I want to pop to the root view when a flow is finished in SwiftUI. How can I do this? #10

Open Rylaa opened 2 months ago

Rylaa commented 2 months ago

I have a flow that continues with push, and when the flow is finished, I want to return to the dashboard, but I couldn't figure out how to do it.

Rylaa commented 2 months ago

how can i do? .popToRoot(DashboardView.self)

trunghvbk commented 1 month ago

You can use .popToRoot In the below sample code, you can see we use it to back from BView to root view (ContentView)

import SwiftUI
import Coordinator

@main
struct CoordinatorTestApp: App {
    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}

enum ContentDestination {
    case aView
}

class ContentCoordinator: AppKitOrUIKitWindowCoordinator<ContentDestination> {
    override func transition(for route: ContentDestination) -> ViewTransition {
        switch route {
        case .aView:
            return .push(AView())
        }
    }
}

struct ContentView: View {
    @StateObject var coordinator = ContentCoordinator()
    var body: some View {
        VStack {
            Button {
                coordinator.trigger(.aView)
            } label: {
                Text("Go To AView")
            }
        }
        .padding()
        .coordinator(coordinator)
    }
}

struct AView: View {
    @StateObject var coordinator = ACoordinator()

    var body: some View {
        VStack(spacing: 16) {
            Button {
                coordinator.trigger(.popBack)
            } label: {
                Text("Back")
            }

            Button {
                coordinator.trigger(.bView)
            } label: {
                Text("Go To BView")
            }
        }
        .coordinator(coordinator)
    }
}

enum ADestination {
    case popBack
    case bView
}

class ACoordinator: AppKitOrUIKitWindowCoordinator<ADestination> {
    override func transition(for route: ADestination) -> ViewTransition {
        switch route {
        case .popBack:
            return .pop
        case .bView:
            return .push(BView())
        }
    }
}

struct BView: View {
    @StateObject var coordinator = BCoordinator()

    var body: some View {
        VStack {
            Button {
                coordinator.trigger(.popToRoot)
            } label: {
                Text("Back To Root")
            }
        }
        .coordinator(coordinator)
    }
}

enum BDestination {
    case popToRoot
}

class BCoordinator: AppKitOrUIKitWindowCoordinator<BDestination> {
    override func transition(for route: BDestination) -> ViewTransition {
        switch route {
        case .popToRoot:
            return .popToRoot
        }
    }
}