TextField not updating

the following code loads fine, the text and the double field both show 300. however when I click submit the text only changes to 0. you will see in the print output that the init was called with the new value of 0 but it does not update the double field? any suggestions?


import SwiftUI

struct ContentView: View {
  @State var amount:Double = 300
  var body: some View {
  VStack {
  Text("\(self.amount)")
  DoubleField(value: $amount)
  Button(action: {self.amount=0}) {Text("Submit")}
  }
  .padding()
  .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct DoubleField:View {

  @Binding var doubleValue:Double
  @State var stringValue:String

  init(value: Binding) {
  print("DoubleField.init(value: \(value.wrappedValue))")
  self._doubleValue = value
  self._stringValue = State(initialValue: "\(value.wrappedValue)")
  }

  var body: some View {
  TextField("0.00", text: $stringValue)
  }

}

Instead of introducing the additional stringValue state property and trying to keep that in sync with the doubleValue binding you can utilize the doubleValue binding directly in the textfield with a formatter to do the double to string conversion


TextField("0.00", value: $doubleValue, formatter: NumberFormatter())
TextField not updating
 
 
Q