SwiftUI: Changing Button Text based on some external event

I am a newbie to SwiftUI. I have a button with some text. I want to change the text of that button when some external event happens. For example take the string typed in a Text Box and show that as text in the button.
Please share a way to do this. Thanks
Answered by OmerFlame in 642490022
Here's how to make the example you proposed:

Code Block swift
import SwiftUI
struct ContentView: View {
@State var buttonText = ""
var body: some View {
VStack {
TextField("Text Here", text: $buttonText)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(self.buttonText) {
/* code to be executed when button is pressed */
}
}
}
}


I suggest that you read about the @State property wrapper and how SwiftUI Views work in general.

In short, SwiftUI is a state-driven UI framework, meaning that every variable which is somehow displayed on screen that you change at some point in time will immediate refresh the view with the new data. It makes updating things and listening to changes an absolute breeze.

I hope I helped!
Declare an @State variable and use it as the label text of the Button.
Code Block
import SwiftUI
struct ContentView: View {
@State var buttonTitle: String = ""
var body: some View {
VStack {
TextField("Input text:", text: $buttonTitle)
Button(buttonTitle) {
print("\(buttonTitle) pressed")
}
}
}
}


Accepted Answer
Here's how to make the example you proposed:

Code Block swift
import SwiftUI
struct ContentView: View {
@State var buttonText = ""
var body: some View {
VStack {
TextField("Text Here", text: $buttonText)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(self.buttonText) {
/* code to be executed when button is pressed */
}
}
}
}


I suggest that you read about the @State property wrapper and how SwiftUI Views work in general.

In short, SwiftUI is a state-driven UI framework, meaning that every variable which is somehow displayed on screen that you change at some point in time will immediate refresh the view with the new data. It makes updating things and listening to changes an absolute breeze.

I hope I helped!

Cool, this example code save my day and my app works in the way I have thought thanks to this examples the lead me to the right way!

My solution looks like this

    @State var counter = 0
    @State var buttonTitle = "Klick mich!"
    var body: some View {
        VStack {
            // other controls
            Button(buttonTitle) {
                counter += 1
                buttonTitle = "\(counter) mal\(counter > 1 ? "e":"") geklickt"
            }
        }
SwiftUI: Changing Button Text based on some external event
 
 
Q