1

I am creating a text control which accepts optional text value. If the value is provided I would like to show TextField control otherwise use Text Control. Can you please guide me how can I rebind already binded value to a text field

struct TextBoxControl: View {
    var text : String
    @Binding var value : String?
    
    var body: some View {
        if (value == nil )
        {
            Text(text)
        }
        else
        {
            TextField("Enter value", text: $value!)
        }
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
Musti
  • 63
  • 7
  • 1
    Does this answer your question? [SwiftUI Optional TextField](https://stackoverflow.com/questions/57021722/swiftui-optional-textfield) – lorem ipsum Apr 26 '21 at 19:33

2 Answers2

1

Great I found a solution

//'''
struct TextBoxControl: View {
var text : String
//@Binding var value : String?
var value : Binding<String>?


@State var dummyText : String = ""

var body: some View {
    if (value == nil )
    {
        Text(text)
    }
    else
    {
        TextField("Enter value", text: (value!) ?? $dummyText)
    }
}
}
struct TextBoxControlTest: View {
var text : String
@State var txt : String
//var value : Binding<String>?


@State var dummyText : String = ""

var body: some View {
    TextBoxControl(text: "ddd", value: ($txt))
}
}
//'''
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
Musti
  • 63
  • 7
  • You could replace your `$dummyText` with `.constant("")` in order to avoid creating the `@State var dummyText` only for that :) – AlbertUI Apr 27 '21 at 11:15
0

It is much simpler for your case, just

TextField("Enter value", text: Binding($value)!)
Asperi
  • 228,894
  • 20
  • 464
  • 690