1

I am trying to have the TextField to return the value in the fly rather than the user having to pressed the return key for the value to be stored. With the current code below, the user has to press enter for value to bind with the variable. The problem is if there are multiple fields and the user just taps through them then this field will not bind. Plus the numberPad keyboard type does not have a return key.

Would appreciate the help.

struct ContentView: View {

    @State var number = 0

    var formatter: NumberFormatter = {
       let f = NumberFormatter()
        f.isLenient = true
        return f
    }()

    var body: some View {
        Form {
            Section {
                TextField("Price", value: $number, formatter: formatter)
                     .keyboardType(.numberPad)
                Text("\(number)")
            }
        }
    }
}
oalansari82
  • 107
  • 3
  • 6
  • 1
    This is a known behaviour of current SwiftUI TextField with formatter. You can try alternate approach provided in [Use Binding with a TextField SwiftUI](https://stackoverflow.com/a/59509242/12299030) – Asperi Jun 12 '20 at 04:24
  • That worked smoothly. Thank you for pointing it out. Though I've noticed that the field does not accept keyboard types. Any idea on how I can make it work? – oalansari82 Jun 12 '20 at 04:56
  • Ok I think I got it working. However one more issue popped up. When I have a double the initial value in the field is 0.0 and the replacing method does not allow me to delete the value in the field. – oalansari82 Jun 12 '20 at 05:07

0 Answers0