Change the root view of UIHostingController in SwiftUI
let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
if let windowScenedelegate = scene?.delegate as? SceneDelegate {
let window = UIWindow(windowScene: scene!)
window.rootViewController = UIHostingController(rootView:ContentView())
windowScenedelegate.window = window
window.makeKeyAndVisible()
}
By using this we can change the rootView in any button click by implementing the above code.
Declare an AppRootView, something like this:
struct AppRootView: View {
@ObservedObject private var auth: Auth
var body: some View {
Group {
if auth.token != nil {
MainTabbedView()
} else {
StartRegistrationView()
}
}
}
}
and then in SceneDelegate set it as the root view:
window.rootViewController = UIHostingController(rootView: AppRootView(auth: $auth))
You have to bind your view to your Auth() either by passing it in as I did above or by setting it on your environment. The beauty of SwiftUI is that as soon as the token is not nil, the view will redraw and your user will find them selves in MainTabbedView.