How to show conditional views in SwiftUI

DevTechie Inc
Dec 7, 2022

In this article, we will see how to present conditional views in SwiftUI.

Let’s start with two views. We will have a login view and home view.

Login View

Login view will take loggedIn boolean value as a binding parameter and upon clicking the login button it will change the state for the calling page.

struct LoginView: View {
    @Binding var loggedIn: Bool
    
    @State private var username = ""
    @State private var password = ""
    
    var body: some View {
        VStack {
            Text("DevTechie Login")
                .font(.largeTitle)
            
            TextField("Enter username", text: $username)
                .textFieldStyle(.roundedBorder)
            
            SecureField("Enter password", text: $password)
                .textFieldStyle(.roundedBorder)
            
            Button {
                loggedIn.toggle()
            } label: {
                Label("Login", systemImage: "lock.shield.fill")
            }
            .buttonStyle(.bordered)}
    }
}

Home View
struct DevTechieHome: View {
    var body: some View {
        Text("Welcome home, DevTechie")
            .font(.largeTitle)
    }
}

Main View
This is where we will apply if else condition where if the loggedIn state variable is true, we will show Home view otherwise we will show Login view.

struct ConditionalViewsSwiftUI: View {
    @State private var loggedIn = false
    
    var body: some View {
        VStack {
            if loggedIn {
                DevTechieHome()
            } else {
                LoginView(loggedIn: $loggedIn)
            }
        }
    }
}
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to follow 😍. Also subscribe our newsletter at https://www.devtechie.com