Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally show Navigation View

Since only one NavigationView should be used in the view hierarchy, how do you deal with the case where the initial view to be presented is determined at app start?

@main
struct heartbreaksApp: App {
    let token = UserDefaults.standard.value(forKey: "token")

    var body: some Scene {
        return WindowGroup {
            if token != nil {
                Campaigns()

            } else {
                Login()
            }
        }
    }
}

So if the token is nil, we'll go to the Login where a NavigationView is declared, when we login a NavigationLink takes us to Campaigns view. However, if the token is not nil we're taken directly to the Campaigns view where we have no Navigation View and so cannot navigate from there to other views. If I do declare a Navigation View in Campaigns too, I'll end up with two causing all kinds of havoc, 2 back buttons for instance, one pointing to Login and one pointing to Campaigns. I'm obviously doing this wrong...Please see picture

like image 886
jesper Avatar asked Jun 27 '26 03:06

jesper


1 Answers

Remove NavigationView from login and place it at top level, like

NavigationView {           // << here !!
    if token != nil {
        Campaigns()
    } else {
        Login()
    }
}
like image 78
Asperi Avatar answered Jun 30 '26 17:06

Asperi