Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present a view full-screen in SwiftUI?

I worked to a login view, now I want to present the view after login, but I do not want the user to have the possibility to return to the login view. In UIkit I used present(), but it seems in SwiftUI presentation(_ modal: Modal?) the view does not take the entire screen. Navigation also isn't an option.

Thank you!

like image 287
Sorin Lica Avatar asked Jun 12 '19 08:06

Sorin Lica


3 Answers

struct ContentView: View {
    @EnvironmentObject var userAuth: UserAuth 
    var body: some View {
        if !userAuth.isLoggedin {
            return AnyView(LoginView())
        } else {
            return AnyView(HomeView())
        }
    }
}
like image 110
Chetan Hedamba Avatar answered Oct 23 '22 05:10

Chetan Hedamba


I do not want the user to have the possibility to return to the login view

In that case you shouldn't be presenting away from the login view but replacing it entirely.

You could do this by conditionally building the login view or the "app view".

Something like this...

// create the full screen login view
struct LoginView: View {
    // ...
}

//create the full screen app veiw
struct AppView: View {
    // ...
}

// create the view that swaps between them
struct StartView: View {
    @EnvironmentObject var isLoggedIn: Bool // you might not want to use this specifically.

    var body: some View {
        isLoggedIn ? AppView() : LoginView()
    }
}

By using a pattern like this you are not presenting or navigating away from the login view but you are replacing it entirely so it is no longer in the view hierarchy at all.

This makes sure that the user cannot navigate back to the login screen.

Equally... by using an @EnvironmentObject like this you can edit it later (to sign out) and your app will automatically be taken back to the login screen.

like image 27
Fogmeister Avatar answered Oct 23 '22 05:10

Fogmeister


Encapsulate the body in a Group to eliminate compiler errors:

struct StartView: View {

@EnvironmentObject var userAuth: UserAuth

var body: some View {
    Group {
        if userAuth.isLoggedin {
            AppView()
        } else {
            LoginView()
        }

    }
}
like image 5
Frank Möller Avatar answered Oct 23 '22 05:10

Frank Möller