How can I launch a SwiftUI View without Navigation back tracking?

Viewed 2702

I want to launch a View as a standalone View without the navigation hierarchy. The reason that I don't want to use a NavigationButton is that I don't want the user to return to the calling form.

I have tried the following approach that is similar to how the first view is launched in ScenceDelegate but nothing happens:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let window = appDelegate.getNewWindow()
    window.rootViewController = UIHostingController(rootView: NewView())
    window.makeKeyAndVisible()

I have a legitimate reason not to use the navigation UI, I'm leaving the explanation out to keep this short. I'm avoiding Storyboards to keep this as a simple as possible.

Thank you for any solution suggestions.

1 Answers

This is how I accomplished loading a new root View.

I added the following to the AppDelegate code

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
     var window: UIWindow?

   ...

    func loadNewRootSwiftUIView(rootViewController: UIViewController)
    {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = rootViewController
        self.window = window
        window.makeKeyAndVisible()
    }
}

And placed the following in my form:

struct LaunchView : View {
    var body: some View {
        VStack {
            Button(
                action: {
                   LaunchLoginView()
            },
                label: {
                    Text("Login")
            }
            )
        }
    }
}

func LaunchLoginView(){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let vContoller = UIHostingController(rootView: LoginView())
    appDelegate.loadNewRootSwiftUIView(rootViewController: vContoller)
}
Related