简体   繁体   English

SwiftUI 使用按钮更改视图

[英]SwiftUI Change View with Button

I understand there is PresentationButton and NavigationButton in order to change views in the latest SwiftUI.我知道有 PresentationButton 和 NavigationButton 可以在最新的 SwiftUI 中更改视图。 However I want to do a simple operation like below.但是我想做一个简单的操作,如下所示。 When user clicks on SignIn button if credentials are correct it will sign them in but also do a segue (in this case change the view).当用户单击“登录”按钮时,如果凭据正确,它将登录并执行 segue(在这种情况下更改视图)。 However I could not check if they are correct in PresentationButton and I could not change the view in a normal button.但是,我无法在 PresentationButton 中检查它们是否正确,也无法更改普通按钮中的视图。 Is there another way to do that?有没有另一种方法可以做到这一点?

  @IBAction func signInClicked(_ sender: Any) {

        if emailText.text != "" && passwordText.text != "" {

            Auth.auth().signIn(withEmail: emailText.text!, password: passwordText.text!) { (userdata, error) in
                if error != nil {
                   //error
                } else {

                   performSegue(withIdentifier: "toFeedActivity", sender: nil)


                }
            }

        } else {
            //error
        }




    }

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.")
        }
    }
}

I had the same need in one of my app and I've found a solution...我在我的一个应用程序中有同样的需求,我找到了一个解决方案......

Basically you need to insert your main view in a NavigationView, then add an invisible NavigationLink in you view, create a @state var that controls when you want to push the view and change it's value on your login callback...基本上你需要在 NavigationView 中插入你的主视图,然后在你的视图中添加一个不可见的 NavigationLink,创建一个 @state var 来控制你何时想要推送视图并在你的登录回调中更改它的值......

That's the code:那是代码:

struct ContentView: View {
    @State var showView = false
    var body: some View {
        NavigationView {
            VStack {
                Button(action: {
                    print("*** Login in progress... ***")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                        self.showView = true
                    }
                }) {
                    Text("Push me and go on")
                }

                //MARK: - NAVIGATION LINKS
                NavigationLink(destination: PushedView(), isActive: $showView) {
                    EmptyView()
                }
            }
        }
    }
}


struct PushedView: View {
    var body: some View {
        Text("This is your pushed view...")
            .font(.largeTitle)
            .fontWeight(.heavy)
    }
}

Try with state & .sheet尝试使用 state 和 .sheet

struct ContentView: View {
    @State var showingDetail = false

    var body: some View {
        Button(action: {
            self.showingDetail.toggle()
        }) {
            Text("Show Detail")
        }.sheet(isPresented: $showingDetail) {
            DetailView()
        }
    }
}

You can use navigation link with tags so,您可以使用带有标签的导航链接,

Here is the code:这是代码:

first of all, declare tag var首先,声明标签var

@State var tag : Int? = nil

then create your button view:然后创建您的按钮视图:

Button("Log In", action: {
                        Auth.auth().signIn(withEmail: self.email, password: self.password, completion: { (user, error) in
                            if error == nil {
                                self.tag = 1
                                print("success")
                            }else{
                                print(error!.localizedDescription)
                            }
                        })

So when log in success tag will become 1 and when tag will become 1 your navigation link will get executed因此,当登录成功标签将变为 1 并且当标签变为 1 时,您的导航链接将被执行

Navigation Link code:导航链接代码:

NavigationLink(destination: HomeView(), tag: 1, selection: $tag) {
                EmptyView()
                }.disabled(true)

if you are using Form use .disabled because here the empty view will be visible on form and you don't want your user to click on it and go to the homeView.如果您使用 Form 使用 .disabled 因为这里空视图将在表单上可见并且您不希望您的用户单击它并转到 homeView。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM