在 SwiftUI 中动态更改货币格式
我正在尝试制作一个非常简单的应用程序,当用户选择其首选货币时,它会更改文本字段的格式
struct ContentView: View {
@State var currency = "EUR"
@State var amount = 0.0
let currencies = ["GBP", "USD", "EUR", "WON", "LKR"]
var body: some View {
Form {
TextField(
"Amount",
value: $amount,
format: .currency(code: currency)
)
Picker("Currency", selection: $currency) {
ForEach(currencies, id: \.self) {
Text($0)
}
}
.pickerStyle(.segmented)
Section {
Text("Selected: \(currency)")
}
}
.navigationTitle("Currency Picker Issue")
}
}
此尝试有两个主要问题:
- 选择新货币实际上并没有改变格式金额字段的
- 输入金额中的新值不会保存该值(一旦字段失去焦点,它就会返回零
为什么会发生这种情况?
有没有办法在 SwiftUI 中实现类似的东西?
I'm trying to make a dead simple app that changes the format of a text field when the user selects their preferred currency
struct ContentView: View {
@State var currency = "EUR"
@State var amount = 0.0
let currencies = ["GBP", "USD", "EUR", "WON", "LKR"]
var body: some View {
Form {
TextField(
"Amount",
value: $amount,
format: .currency(code: currency)
)
Picker("Currency", selection: $currency) {
ForEach(currencies, id: \.self) {
Text($0)
}
}
.pickerStyle(.segmented)
Section {
Text("Selected: \(currency)")
}
}
.navigationTitle("Currency Picker Issue")
}
}
With this attempt there are two main issues:
- Selecting a new currency doesn't actually change the format of the amount field
- Entering a new value into the amount does not save the value (it shoots back to zero as soon as the field loses focus
Why is this happening?
Is there any way to implement something like this in SwiftUI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的 1. 问题,您可以通过在 TextField 上使用
.id
来强制 SwiftUI 重绘:您的 2. 问题我无法重现,至少只要您输入有效的金额。
For you 1. issue, you can force SwiftUI to redraw by using
.id
on the TextField:your 2. issue I cannot reproduce, at least as long as you enter a valid amount.