我在表单上有一个文本字段,用户可以在其中键入值,但我还想用一个按钮更新文本字段的内容。
这是我的代码:
struct test: View {
@State private var amount: Double = 0.0
var body: some View {
Form {
VStack {
HStack {
Text("Amount EUR")
Spacer()
TextField("Type amount", value: $amount, format: .number)
.keyboardType(.numberPad)
.multilineTextAlignment(.trailing)
}
Text("Set MAX (999)")
.frame(maxWidth: .infinity, alignment: .leading)
.onTapGesture {
print("before tap \(amount )")
amount = 999
print("after tap \(amount)")
}
}
}
}
当我刚刚启动该应用程序时,第一次点击文本会将文本字段更新为 999,但之后它就不再起作用了。
amount
值已正确更新,但文本字段未反射(reflect)更改。
你能解释一下吗?
最佳答案
答案很简单,TextFields
在获得焦点时不会更新。要解决此问题,您需要在 View 中加入一个@FocusState
,并使TextField
在更新变量之前失去焦点。您可以在点击 TextField
之前点击您的 Text
以在您自己的 View 中对其进行测试。您会看到它更新得很好。
struct ButtonUpdateTextField: View {
@State private var amount: Double = 0.0
@FocusState var isFocused: Bool // <-- add here
var body: some View {
Form {
VStack {
HStack {
Text("Amount EUR")
Spacer()
TextField("Type amount", value: $amount, format: .number)
.keyboardType(.numberPad)
.multilineTextAlignment(.trailing)
.focused($isFocused) // <-- add here
}
Text("Set MAX (999)")
.frame(maxWidth: .infinity, alignment: .leading)
.onTapGesture {
print("before tap \(amount )")
isFocused = false // <-- add here
amount = 999
print("after tap \(amount)")
}
}
}
}
}
关于Swiftui 文本字段在值更改时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71259654/