我创建了一个新的SwiftUI项目,并在视图中添加了文本字段和按钮。如何在按下按钮后读出用户在文本字段中输入的内容并使用if-语句?
当前代码:
var body: some View {
VStack {
Text("Hello!").font(.system(size: 32, design: .rounded))
TextField("Write something..").multilineTextAlignment(.center)
Button() {
Text("Send")
}
}
}
谢谢!
您需要绑定来存储输入的文本,然后可以在按钮的动作处理程序中阅读它:
@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")
}
}
}
[TextField
是必需参数是placeholder
和text
。
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")
}
}
}
}