Home > Software design >  Login Screen SwiftUI
Login Screen SwiftUI

Time:07-06

I have TextFields for Login and SecureField for Password. How can I go to another view when my Login and Password are correct?

struct LoginBoard: View {
@State private var login = "Tony"
@State private var password = "1234"

var body: some View {
    
    ZStack { 
        VStack {
            HStack {
                Text("Enter Login and Password")
            }

            HStack {
                Image(systemName: "person")
                TextField("Login", text: $login)
            }
            
            HStack {
                SecureField("Password", text: $password)
            }
            
            Button("Login") {
                   
            }
         }
      }
   }
}

CodePudding user response:

you should NavigationView that equivalent to navigation controller in UIKit and use NavigationLink as the segue or trigger for navigation

struct LoginBoard: View {
 @State private var login = "Tony"
 @State private var password = "1234"
 @State isLoginSuccess = False

  var body: some View {
 // like navigation controller that handles the navigation of views
 NavigationView{ 
 // DestinationView is the view will go to if credentials is correct
 NavigationLink(destination: DestinationView(), isActive: $isLoginSuccess) { }

ZStack { 
    VStack {
        HStack {
            Text("Enter Login and Password")
        }

        HStack {
            Image(systemName: "person")
            TextField("Login", text: $login)
        }
        
        HStack {
            SecureField("Password", text: $password)
        }
        
        Button("Login") {
              // if user and password are correct change isLoginSuccess to true and will navigate to the next View 
        isLoginSuccess = true
        }
     }
  }
  }
 }
 }

CodePudding user response:

Wrap your Stacks inside a NavigationView{} and use a NavigationLink{} to direct to another view. Sample code is below:

import SwiftUI

struct LoginBoard: View { 

@State private var login = "Tony"
@State private var password = "1234"

var body: some View {
NavigationView {
    ZStack {
        VStack {
            HStack {
                Text("Enter Login and Password")
            }

            HStack {
                Image(systemName: "person")
                TextField("Login", text: $login)
            }
            
            HStack {
                SecureField("Password", text: $password)
            }
            NavigationLink {
                WelcomeView()
            } label: {
                Text("Login")
                    .foregroundColor(.blue)
            }
            .disabled((login == "Tony" && password == "1234") ? false : true)
         }
      }
   }
}
}


struct WelcomeView: View {
var body: some View {
    Text("welcome!")
}
}
  • Related