【问题标题】:How to set text for TextField in SwiftUI on button click如何在按钮单击时在 SwiftUI 中为 TextField 设置文本
【发布时间】:2019-12-13 06:09:40
【问题描述】:

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

【问题讨论】:

  • 您能发布到目前为止您尝试过的内容吗?
  • //TextFields 状态 @State var textFieldText:String = "" //TextField 代码 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( .nu​​mberPad) .cornerRadius(10) //On button Click self.$textFieldText = "Changed Text"

标签: ios swift swiftui


【解决方案1】:

试试下面的代码(在 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")
           }
       }
   }
}

【讨论】:

    【解决方案2】:

    您可以创建类似按钮的动作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多