Search code examples
swiftuiios13lottieios-navigationview

Change between views on SwiftUI within NavigationView


today I'm trying to navigate between 2 different views but I want to use the same view cleaning the info from the previous view. I created a MotherView to invoke 2 different view. Here's my code

import SwiftUI

struct MotherView: View {
    @ObservedObject var viewRouter: ViewRouter

    var body: some View {

        VStack {
            if viewRouter.currentPage == "splash" {
                SplashView()
            } else{
                ContentView()
            }
        }
    }
}


struct MotherView_Previews : PreviewProvider {
    static var previews: some View {
        MotherView(viewRouter: ViewRouter())
    }
}

This is my SplashScreen:

    struct SplashView: View {
    @State private var isAnimated = true
    @EnvironmentObject var pageSettings: PageSettings

    var body: some View {
            VStack{

                LottieView(filename:"Logo")
                pageSettings.currentPage = "content"
            }
    }


}

NOTE SplashView() is a view with an animation using Lottie and ContentView() is a view with my login. I want to start my app using my SplashView() and then clean the VStack and run the ContentView().

Is That possible? Thank you!

This is the last update from this code (I got this error: "Argument type '()' does not conform to expected type 'View'")

    struct SplashView: View {
    @State private var animated = false
    @EnvironmentObject var pageSettings: PageSettings
    var body: some View {
        VStack{
            if self.animated{
                pageSettings.currentPage = "content"
            }else{
                LottieView()
            }
        }
    }
}

Solution

  • I use a similar technic to show a login view and then the content view after the user logged in. Here's a way you can achieve that:

    Create an ObservableObject

    class pageSettings: ObservableObject {
        @Published var currentPage: String = "splash"
    }
    

    Modify your SceneDelegate

    Add following line after var window: UIWindow? :

    var pageSettings = PageSettings()
    

    Then replace the call of UIHostingController:

    window.rootViewController = UIHostingController(rootView: contentView)
    

    by this call:

    window.rootViewController = UIHostingController(rootView: contentView.environmentObject(pageSettings))
    

    Use your ObservableObject

    Inside your MotherView, add this property:

    @EnvironmentObject var pageSettings: PageSettings
    

    Replace your test by this:

    if pageSettings.currentPage == "splash" 
    

    Inside your SplashScreen

    You also need to call the EnvironmentObject. You can then update the value of currentPage like this (it will instantly switch view):

    pageSettings.currentPage = "content"
    

    You can use your environment object to pass data between all your views.