A possible solution is to create an ObservableObject
that is responsible for routing:
enum AppView {
case login, main
}
class ViewRouter: ObservableObject {
// here you can decide which view to show at launch
@Published var currentView: AppView = .login
}
Then, you can inject this ViewRouter
as an EnvironmentObject
to the root view:
@main
struct TestApp: App {
@StateObject private var viewRouter = ViewRouter()
var body: some Scene {
WindowGroup {
RootView()
.environmentObject(viewRouter)
}
}
}
Now you can change the current view from any view:
struct RootView: View {
@EnvironmentObject private var viewRouter: ViewRouter
var body: some View {
VStack {
if viewRouter.currentView == .login {
LoginView()
} else if viewRouter.currentView == .main {
MainView()
}
}
}
}
struct LoginView: View {
@EnvironmentObject private var viewRouter: ViewRouter
var body: some View {
VStack {
Text("Login View")
Button("Log in") {
viewRouter.currentView = .main
}
}
}
}
struct MainView: View {
@EnvironmentObject private var viewRouter: ViewRouter
var body: some View {
VStack {
Text("Main View")
Button("Log out") {
viewRouter.currentView = .login
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…