选择器选择更改 SwiftUI 中的 TextField

发布于 2025-01-18 23:55:56 字数 781 浏览 5 评论 0原文

我希望用户能够选择他们想要放入我的应用程序中的货币。但使用此代码:

import SwiftUI

struct ContentView: View {
    
    @State private var amount = 0.0
    @State private var currency = "USD"
    
    let currencies = ["PLN", "USD", "EUR", "GBP", "JPY"]
    
    var body: some View {
            Form {
                
                Picker("Currency", selection: $currency) {
                    ForEach(currencies, id: \.self) {
                        Text($0)
                    }
                }
                
                TextField("Amount", value: $amount, format: .currency(code: currency))
                    .keyboardType(.decimalPad)
            }
            }
      
    }

使用 Picker 进行的货币选择不会更改 TextField 中的货币类型(它始终保持美元,即使在删除后也是如此)。如何将所选的货币代码推送到文本字段?

I want the user to be able to choose the currency they want to put in my app. But with this code:

import SwiftUI

struct ContentView: View {
    
    @State private var amount = 0.0
    @State private var currency = "USD"
    
    let currencies = ["PLN", "USD", "EUR", "GBP", "JPY"]
    
    var body: some View {
            Form {
                
                Picker("Currency", selection: $currency) {
                    ForEach(currencies, id: \.self) {
                        Text($0)
                    }
                }
                
                TextField("Amount", value: $amount, format: .currency(code: currency))
                    .keyboardType(.decimalPad)
            }
            }
      
    }

The currency choices made with Picker don't change the currency type in the TextField (it stays USD at all times, even after deletion). How to push the chosen currency code to the TextField?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

梦晓ヶ微光ヅ倾城 2025-01-25 23:55:56

不会跟踪格式来更新 TextField,您可以根据格式参数使用 id 强制执行此操作,例如

 TextField("Amount", value: $amount, format: .currency(code: currency))
      .keyboardType(.decimalPad)
      .id(currency)                // << here !!

使用 Xcode 13.2 / iOS 15.2 进行测试

Format is not tracked to update TextField, you can do it forcefully using id depending on format parameter, like

 TextField("Amount", value: $amount, format: .currency(code: currency))
      .keyboardType(.decimalPad)
      .id(currency)                // << here !!

Tested with Xcode 13.2 / iOS 15.2

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