'How can I display text when a button is pressed? SwiftUI
@State var email: String = ""
var body: some View {
TextField("[email protected]", text: $email)
Button {
} label: {
Text("Send verification code")
}
}
I am trying to make a button called "send verification code" so that if users input something into the text field and press the button, then the code returns the text "Verification code sent".
(sorry I am a beginner)
Solution 1:[1]
You can conditionally show the button or a simple Text.
The button action toggles a boolean flag which swaps the views.
@State private var email = ""
@State private var confirm = false
var body: some View {
VStack {
TextField("[email protected]", text: $email)
if confirm {
Text("Verification code sent")
.foregroundColor(.green)
} else {
Button(action: submit) {
Text("Send verification code")
}
}
}
}
func submit() {
withAnimation {
confirm = true
}
}
Alternatively use the button to display the confirmation text and disable user interaction
var body: some View {
VStack {
TextField("[email protected]", text: $email)
Button(action: submit) {
Text(confirm ? "Verification code sent" : "Send verification code")
}
.tint(confirm ? .green : .blue)
.allowsHitTesting(!confirm)
}
}
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 |
