在 SwiftUI 中动态更改货币格式

发布于 2025-01-15 00:38:55 字数 1049 浏览 2 评论 0原文

我正在尝试制作一个非常简单的应用程序,当用户选择其首选货币时,它会更改文本字段的格式

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")
    }
}

Result

此尝试有两个主要问题:

  1. 选择新货币实际上并没有改变格式金额字段的
  2. 输入金额中的新值不会保存该值(一旦字段失去焦点,它就会返回零

为什么会发生这种情况?

有没有办法在 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")
    }
}

Result

With this attempt there are two main issues:

  1. Selecting a new currency doesn't actually change the format of the amount field
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷雨优美回忆 2025-01-22 00:38:58

对于您的 1. 问题,您可以通过在 TextField 上使用 .id 来强制 SwiftUI 重绘:

        TextField(
            "Amount",
            value: $amount,
            format: .currency(code: currency)
        )
            .id(currency) // forces redraw of view when changed

您的 2. 问题我无法重现,至少只要您输入有效的金额。

For you 1. issue, you can force SwiftUI to redraw by using .id on the TextField:

        TextField(
            "Amount",
            value: $amount,
            format: .currency(code: currency)
        )
            .id(currency) // forces redraw of view when changed

your 2. issue I cannot reproduce, at least as long as you enter a valid amount.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文