简体   繁体   中英

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

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")
           }
       }
   }
}

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")
           }
       }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM