简体   繁体   中英

Currency input in SwiftUI TextField

I am trying to implement the ability to change a currency value in an edit mode detailed view, but I am struggling to get formatted input for numeric values working.

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...

The data is passed in correctly, and the textfield displays the formatted value which is stored in $jobDetails.hourlyRateBasic, however, I cannot edit the field as I would be able to if it were a string. If I try to edit the field then press enter in the simulator, I get the following error message:

[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.

FYI $jobDetails.hourlyRateBasic is of type double.

I have created a component that wraps around a UITextfield.

You can check it out here https://github.com/youjinp/SwiftUIKit

Here's the demo

货币文本字段演示

Ben Scheirman created a Tip Calculator that used a TextField with a currency formatter. The difference between his code and yours is that he stored the currency value in a Double?. NumberFormatter returns a NSNumber?.

You can see his code at https://github.com/nsscreencast/397-swiftui-tip-calculator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM