4

I want to set text for Textfield in SwiftUI on button clicked. I tried using @State variable but its giving error

2
  • Can you post what you've tried so far? Commented Dec 13, 2019 at 6:10
  • //TextFields States @State var textFieldText:String = "" //TextField Code TextField("Enter some text", text: $textFieldText) .padding(.all, 9.0) .frame(width: 350, height: 50.0) .onTapGesture(count: 1, perform: { print("=====Tapped======") }) .border(Color.green, width: 4) .keyboardType(.numberPad) .cornerRadius(10) //On button Click self.$textFieldText = "Changed Text" Commented Dec 13, 2019 at 6:20

2 Answers 2

9

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")
           }
       }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.