Dhananjay Patil
Dhananjay Patil

Reputation: 452

How to set text for TextField in SwiftUI on button click

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

Answers (2)

bhavik
bhavik

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

Rohit Makwana
Rohit Makwana

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

Related Questions