Can SwiftUI Text Fields work with optional Bindings? Currently this code:
struct SOTestView : View {
@State var test: String? = \"Test\"
var body: s
True, at the moment TextField in SwiftUI can only be bound to String variables, not String?.
But you can always define your own Binding like so:
import SwiftUI
struct SOTest: View {
@State var text: String?
var textBinding: Binding {
Binding(
get: {
return self.text ?? ""
},
set: { newString in
self.text = newString
})
}
var body: some View {
TextField("Enter a string", text: textBinding)
}
}
Basically, you bind the TextField text value to this new Binding binding, and the binding redirects it to your String? @State variable.