如何在单击按钮时在SwiftUI中为TextField设置文本

时间:2019-12-13 06:09:40

标签: ios swift swiftui

我想在单击按钮的Textfield中为SwiftUI设置文本。我尝试使用@State变量,但变量给出错误

2 个答案:

答案 0 :(得分:4)

尝试以下代码(已在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")
           }
       }
   }
}

答案 1 :(得分:0)

您可以创建按钮状波纹管的动作

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