2

I want to replace a view with another view using SwiftUI.

Currently I use either a NavigationView or .sheet to transition to a new view and that works fine stacking views.

However I have not found a way to completely replace a view with another view. For example when the user first lands on the App it will give an option to sign in or create a new account. I want either option to replace the previous view, not present on top of it. Another example is when the user logs out of the app. I want to dismiss my entire stack and replace with login screen. Not just dismiss all overlying views.

The analogy to pre swiftUI would be to replace the rootView.

1 Answer 1

8

You just display each view conditionally in a root view

var body: some View {
   if isLoggedIn {
      HomeView()
   } else {
      LoginView() {
   }
}
Sign up to request clarification or add additional context in comments.

4 Comments

the path will be determined by user input. for example the user will press a button to choose either create account or signup. at that point I am dong .fullScreenCover to show the next view. But I want to dismiss the original root view if I can.
@alionthego, the principle is that you don't dismiss the root. Rather, the root view contains both the login/signup flows (LoginView in my example) and the view of the app that appears after a used has logged in (HomeView). Inside LoginView you can let the user choose whether to login or to signup. Once the user has logged, the isLoggedIn (or whatever other state) is changed, the root view changes from login/signup screens to the home screen
yes, I understand that. previously though it was possible to change the rootViewController so you don't stack views on top of other views that you will not be using anymore. the above user login was just an example. another maybe a user logging out of an app. previously it was common to dismiss the previous root view that got rid of everything else. but now it seams you have to dismiss the stack elements. I guess I will have to adjust my way of thinking if there is no inherent method to dismiss the root view of an app.
@alionthego, there's also no reason to dismiss the root view. Nesting views is extremely cheap in SwiftUI. Every view modifier in SwiftUI returns a wrapping view. Views are just a lightweight structure that describes the view hierarchy - not a collection of view controllers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.