skip to Main Content

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!)
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    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))
    }
    }
    //'''
    

  2. It is much simpler for your case, just

    TextField("Enter value", text: Binding($value)!)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search