'How to use Button SwiftUI correctly?
There is a code that, by pressing the "Sign Up" button at the bottom of the screen, should open another window. But for some reason, when you click on the button, no action occurs.
I need the View to switch when I click on the button.
import SwiftUI
import CoreData
struct LoginView: View {
@State private var email: String = "Email"
@State private var password: String = "Password"
@State private var showSignup: Bool = false
var body: some View {
ZStack {
VStack {
VStack(alignment: .leading) {
VStack {
LoginText
LoginForm
GradientButton(text: "Login")
.frame(maxWidth: .infinity, alignment: .leading)
ForgotPass(text: "Forgor Password")
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding([.top, .horizontal], 40)
.frame(maxWidth: .infinity, alignment: .leading)
.offset(y: 104)
VStack {
Spacer()
Rectangle()
.frame(height: 1)
.foregroundColor(.secondary.opacity(0.4))
VStack {
Button( action: {
showSignup.toggle()
}, label: {
ForgotPass(text: "Sign Up")
})
}
}
}
.background(Color.white)
if showSignup {
SignupView()
}
}
}
Solution 1:[1]
It's working for me without any issues. May be something to do with your other part of view hierarchy. I observed this toggle' behavior, even it didn't work for me once but I am sure root cause is only due to the way navigation and view hierarchy is implemented.
Actually you implement navigation below code should work without any issues (During dismissal of SignupView showSignup boolean always gets reset to false).
Button( action: {
showSignup = true
}, label: {
ForgotPass(text: "Sign Up")
})
If you don't want to use navigation then toggle should work. If toggle is still causing a problem for you then alternatively you can try this (I tried and its working fine)
Button( action: {
showSignup = !showSignup
}, label: {
ForgotPass(text: "Sign Up")
})
Finally you still facing issues then root cause might be with other part of view hierarchy and navigation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Srivathsa |
