SwiftUI-视图控制器

问题描述 投票:0回答:2

我创建了一个新的SwiftUI项目,并在视图中添加了文本字段和按钮。如何在按下按钮后读出用户在文本字段中输入的内容并使用if-语句?

当前代码:

var body: some View {
        VStack {
            Text("Hello!").font(.system(size: 32, design: .rounded))
            TextField("Write something..").multilineTextAlignment(.center)
            Button() {
                Text("Send")
            }
        }
}

谢谢!

ios swift xcode view swiftui
2个回答
0
投票

您需要绑定来存储输入的文本,然后可以在按钮的动作处理程序中阅读它:

@State var text: String = ""

var body: some View {
        VStack {
            Text("Hello!").font(.system(size: 32, design: .rounded))
            TextField("Write something..", text: $text).multilineTextAlignment(.center)
            Button(action: {
                // now you can simply read the value of self.text to see what was entered
            }) {
                Text("Send")
            }
        }
}

0
投票

[TextField是必需参数是placeholdertext

  1. 占位符:字符串
  2. 文本:绑定

NOTE:也可以使用其他一些需要使用的参数

所以我们必须将字符串绑定到text参数。我们可以使用@State

绑定变量
struct ContentView: View {

    @State var textFieldText: String = ""
    var body: some View {
        VStack {
            TextField("Write something..", text: $textFieldText)
               .multilineTextAlignment(.center)
            Button(action: {
               // here you can read the value of self.textFieldText
            }) {
               Text("Send")
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.