Search code examples
buttonswiftuiswiftui-navigationstack

My button is not navigating me back to my page


I am building a sign up page and when I click either the login button or the back button it is not taking me back to the login page. This is the variable:

@Binding var showSignup: Bool

Here is my code for the back button:

Button(action: {
    showSignup = false
}, label: {
    Image(systemName: "arrow.left")
        .font(.title2)
        .foregroundStyle(.gray)
})

Here is my code for the login button:

Button("Login"){
    showSignup = false
}

This is my login page:

struct JoinPage: View{
    @State private var showSignup: Bool = false
    var body: some View {
        NavigationStack {
            LoginPage(showSignup: $showSignup)
                .navigationDestination(isPresented: $showSignup) {
                    SignUp(showSignup: $showSignup)
                }
        }
   }
}

I have no clue why the variable is not flipping to false when I set it equal to false. Any help is appreciated thank you!


Solution

  • You're binding showSignup into 3 sub-views without any true trigger, so I think that's why it didn't work. Following by your comments, I'm assuming this:

    //Going back from SignUp -> JoinPage
    Button("Login") {
        showSignup = true
    }
    

    However, to make it simpler and more readable, I recommend using @Environment(\.dismiss) and removing the showSignup binding.

    struct SignUp: View {
        @Environment(\.dismiss) private var dismiss
    
        var body: some View {
            ...
            Button("Login"){
                dismiss()
            }
            
            Button(action: {
                dismiss()
            }, label: {
                Image(systemName: "arrow.left")
                    .font(.title2)
                    .foregroundStyle(.gray)
            })
        }
    }