SwiftUI TextField 中的货币输入

Jam*_*ock 4 swift swiftui

我正在尝试实现在编辑模式详细视图中更改货币值的功能,但我正在努力获得数值工作的格式化输入。

struct JobDetailView_Edit: View {

@State var jobDetails: JobDetails

var currencyFormatter: NumberFormatter = {
    let f = NumberFormatter()
    f.numberStyle = .currency
    return f
}()

var body: some View {
    Form {

                Section(header: Text("General")) {
                    HStack {
                        Text("Job Name")
                        Spacer()
                        TextField($jobDetails.jobName)
                            .multilineTextAlignment(.trailing)
                    }

                    TextField($jobDetails.hourlyRateBasic, formatter: currencyFormatter)

                }
... other unimportant code...
Run Code Online (Sandbox Code Playgroud)

数据正确传入,文本字段显示存储在 $jobDetails.hourlyRateBasic 中的格式化值,但是,我无法编辑该字段,因为如果它是一个字符串,我可以这样做。如果我尝试编辑该字段,然后在模拟器中按 Enter 键,则会收到以下错误消息:

[SwiftUI] Failure setting binding's value. The supplied formatter does not produce values of type Double. This may be resolved by ensuring the binding and the output of the formatter are of the same type.
Run Code Online (Sandbox Code Playgroud)

仅供参考 $jobDetails.hourlyRateBasic 是 double 类型。

you*_*jin 7

我创建了一个环绕 UITextfield 的组件。

你可以在这里查看https://github.com/youjinp/SwiftUIKit

这是演示

货币文本字段演示