Post

Replies

Boosts

Views

Created

TextField with Double clear button / currency format for string value
I have TextField which was binded to a variable "checkAmount" type Double. I want to create functionality, then the user clicks on the TextField - clear initial value 0.0 so the user doesn't have to delete it themself and also add currency sign after user input: @State private var checkAmount = 0.0 @FocusState private var checkAmountIsFocused: Bool var totalPerPerson: Double { // calculations including (Double(checkAmount) ?? 0) return 0.0 } var body: some View { NavigationStack { Form { Section("Check amount") { HStack { TextField("Enter check amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD")) .keyboardType(.decimalPad) .focused($checkAmountIsFocused) } } }.navigationTitle("We split") .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer() if checkAmountIsFocused { Button("Done") { checkAmountIsFocused = false } } } } } } } The problem is, looks like it's impossible. So I decided to turn the variable "checkAmount" into a String type. But in this case, I can't add a currency sign to the value: @State private var checkAmount = "" @FocusState private var checkAmountIsFocused: Bool var totalPerPerson: Double { // calculations including (Double(checkAmount) ?? 0) return 0.0 } var body: some View { NavigationStack { Form { Section("Check amount") { HStack { TextField("Enter check amount", text: $checkAmount) .keyboardType(.decimalPad) .focused($checkAmountIsFocused) if !checkAmount.isEmpty { Button { checkAmount = "" }label: { Image(systemName: "multiply.circle.fill") } } } } }.navigationTitle("We split") .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer() if checkAmountIsFocused { Button("Done") { checkAmountIsFocused = false } } } } } } } Could someone please tell me the best way to handle it? Looked over the Internet and the usual clear button can be easily used with a string value, but I have no idea how to add a currency sign into the user's input and use it in calculations at the same time. Thank you!
2
0
464
Apr ’24