SwiftUI Change View with Button

前端 未结 4 1904
失恋的感觉
失恋的感觉 2021-02-04 18:48

I understand there is PresentationButton and NavigationButton in order to change views in the latest SwiftUI. However I want to do a simple operation like below. When user click

4条回答
  •  执笔经年
    2021-02-04 18:49

    Here's one way.

    struct AppContentView: View {
        
        @State var signInSuccess = false
        
        var body: some View {
            return Group {
                if signInSuccess {
                    AppHome()
                }
                else {
                    LoginFormView(signInSuccess: $signInSuccess)
                }
            }
        }
    }
    
    struct LoginFormView : View {
        
        @State private var userName: String = ""
        @State private var password: String = ""
        
        @State private var showError = false
        
        @Binding var signInSuccess: Bool
        
        var body: some View {
            VStack {
                HStack {
                    Text("User name")
                    TextField("type here", text: $userName)
                }.padding()
                
                HStack {
                    Text(" Password")
                    TextField("type here", text: $password)
                        .textContentType(.password)
                }.padding()
                
                Button(action: {
                    // Your auth logic
                    if(self.userName == self.password) {
                        self.signInSuccess = true
                    }
                    else {
                        self.showError = true
                    }
                    
                }) {
                    Text("Sign in")
                }
                
                if showError {
                    Text("Incorrect username/password").foregroundColor(Color.red)
                }
            }
        }
    }
    
    struct AppHome: View {
        
        var body: some View {
            VStack {
            Text("Hello freaky world!")
            Text("You are signed in.")
            }
        }
    }
    
    

提交回复
热议问题