1

Hi I want to add $ sign to a TextField when a user is typing. enter image description here

This is my current code.

ZStack(alignment: .leading) {
  if price.isEmpty {
    Text("Enter total budget")
  }
  HStack {
    TextField("", text: $price)
      .keyboardType(.decimalPad)
  }
}

David S
  • 55
  • 7
  • Use a Formatter https://stackoverflow.com/questions/24960621/formatting-input-for-currency-with-nsnumberformatter-in-swift – lorem ipsum Jun 08 '21 at 13:44
  • 1
    it may be reasonable to use the some kinda currency formatter with the `TextField`, it does not do the formatting on the fly during typing but it definitely formats the input value when the edit finishes. – holex Jun 08 '21 at 13:48
  • Does your app only support dollars? – Joakim Danielson Jun 08 '21 at 19:14

1 Answers1

3

currency formatter is the way to go, but if you just want to show a $ in the TextField as you type, you could use something like this: (you can of course combine this approach with a Formatter)

struct ContentView: View {
    @State var price = ""
    
    var body: some View {
        VStack {
            ZStack(alignment: .leading) {
                if price.isEmpty {
                    Text("Enter total budget")
                }
                HStack {
                    TextField("", text: Binding(
                        get: { price },
                        set: { newVal in
                        if price.starts(with: "$") {
                            price = newVal
                        } else {
                            price = "$" + newVal
                        }
                    })).keyboardType(.decimalPad)
                }
            }.padding(20)
            Text("number entered: " + String(price.dropFirst()))
        }
    }
}