Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency input in SwiftUI TextField

Tags:

swift

swiftui

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.

like image 897
James Woodcock Avatar asked Dec 17 '22 16:12

James Woodcock


2 Answers

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

currency text field demo

like image 112
youjin Avatar answered Jan 12 '23 20:01

youjin


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

like image 37
Michael Salmon Avatar answered Jan 12 '23 21:01

Michael Salmon