Reputation: 452
I want to set text for Textfield
in SwiftUI
on button clicked. I tried using @State
variable but its giving error
Upvotes: 4
Views: 10184
Reputation: 1683
You can create the action of button-like bellow
@State var name: String = "My Name is jack"
var body: some View {
VStack {
TextField("Name:", text: $name)
Button(action: {
self.name = "My Name is Tim"
}) {
Text("Change Name")
}
}
}
Upvotes: 2
Reputation: 4875
Try Below code (tested in Xcode: 11.2.1)
struct ContentView: View {
@State var name: String = ""
var body: some View {
VStack {
TextField("Please enter", text: $name)
Button(action: {
self.name = "Hello text"
}) {
Text("Press")
}
}
}
}
Upvotes: 9