1
struct ContentView: View {
    @State private var data: Double?
    var body: some View {
        VStack {
            TextField("",
                      value: $data,
                      formatter: NumberFormatter(),
                      prompt:Text("..."))
                .textFieldStyle(.roundedBorder)
            Button{
                if let _ = data {
                    //...
                }
            }label:{
                Text("send data").foregroundColor(data == nil ? .gray : .black)
            }
        }
        .padding()
    }
}

I would like to have a textfield:

  • Empty: with ... prompt text and button on gray
  • Not empty: content binding to data and button on black

But the above code doesn't works because TexField expects a non optional type. I find a workaround for String types SwiftUI Optional TextField but doesn't apply to Double? because Double doesn't has an empty state ""

Some hint ? ;)

1 Answers1

2

The problem is that you are using a NumberFormatter, use the newer formatting instead introduced with SwiftUI, FormatStyle. It will handle an optional double the way you expect it to.

TextField("", value: $data, format: .number, prompt:Text("..."))
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52