Search code examples
swiftuiviewswiftuiswiftui-navigationlink

Why is part of previous SwiftUI view showing on newly created view


My first initial view for my app is a splash screen:

enter image description here

This screen has code to check if an authToken is available, if it's not then it will toggle the showLogin bool, which in turn causes my view to go to the LoginView(). Else if there is a authToken available, then it calls a function which fetches information about the user, stores it in an Observable Object and then sets showMain bool to true, which in turn changes my view to my main screen.

It works, but whenever it changes view, it puts the previous view at the bottom of the new view. I know I should use a navigation link for this but I can't get it to work properly with my logic and this is the closest I've gotten:

enter image description here

This is my code:

struct Splash: View {

let keychain = KeychainSwift()

@EnvironmentObject var user: userData

@State var showLogin = false
@State var showMain = false

var body: some View {
    NavigationView{
        VStack{
            if(showLogin){
                LoginView()
            }
            if(showMain){
                Main()
            }
            Text("Splash Screen")
                .onAppear(){
                    if(checkLogin()){
                        let authToken = keychain.get("authToken")
                        getDataAPI().getUserData(authToken: authToken!, completion: { response, error in
                            print("Starting")
                            if(error == nil){
                                let code = response!["code"] as? String
                                if(code == "100"){
                                    print("Done")
                                    DispatchQueue.main.async {
                                        user.email = response?["email"] as! String
                                        user.uid = response?["uid"] as! String
                                        user.username = response?["username"] as! String
                                    }
                                    showMain.toggle()
                                }else{
                                    print(error!)
                                }
                            }
                        })
                    }else{
                        showLogin.toggle()
                    }
                }
        }
    }
}
} 

Solution

  • Because they all in VStack, ie. one below another. To solve this you have to remove splash view from view hierarchy, explicitly, like

    VStack{
        if(showLogin){
            LoginView()
        }
        if(showMain){
            Main()
        }
        if !showLogin && !showMain {
           Text("Splash Screen")
             // ... other your code
        }
    }