值更改时 Swiftui Textfield 不更新
我的表单上有一个文本字段,用户可以在其中输入值,但我还想使用按钮更新文本字段的内容。
这是我的代码:
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
值已正确更新,但文本字段未反映更改。
你能解释一下吗?
I have a textfield on a form where user can type value, but I would also like to update the content of the textfield with a button.
Here is my code :
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)")
}
}
}
}
When I just launch the app, the first tap on the Text updates the textfield with 999, but after it does not work anymore.
The amount
value is correctly updated but the textfield does not reflect the change.
Would you have an explanation ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案很简单,
TextFields
在聚焦时不会更新。要解决此问题,您需要将@FocusState
合并到视图中,并导致TextField
在更新变量之前失去焦点。您可以在点击TextField
之前点击Text
在自己的视图中进行测试。你会看到它更新得很好。The answer is simply that
TextFields
don't update while they are in focus. To solve this problem, you need to incorporate a@FocusState
in to the view, and cause theTextField
to lose focus right before updating the variable. You can test it in your own view by tapping yourText
prior to tapping in to theTextField
. You will see it updates just fine.