Home > database >  Toggle view on specific picker value
Toggle view on specific picker value

Time:12-24

I'm trying to show a TextField when "custom" is chosen from the Picker.

struct ContentView: View {
    @State private var color: String = "red" {
        mutating willSet {
            if newValue == "custom" {
                showCutomField = true
            }
            else {
                showCutomField = false
            }
        }
    }
    @State private var customColor: String = ""
    @State private var showCutomField = false
    private var choices = ["red", "green", "blue", "custom"]
    
    var body: some View {
        Form {
            Picker("Color", selection: $color) {
                ForEach(choices, id: \.self) {
                    Text($0)
                }
            }.pickerStyle(.segmented)
            if showCutomField {
                TextField("Color name", text: $customColor)
            }
        }
    }
}

Changing the value of showCustomField in the code does show and hide the field, however, for some reason I am not able to change the value dynamically.

CodePudding user response:

showCustomField can just be a computed property -- no need for mutating willSet. It should be conditional based on color:

struct ContentView: View {
    @State private var color: String = "red"
    @State private var customColor: String = ""
    var showCustomField: Bool {
        color == "custom"
    }
    private var choices = ["red", "green", "blue", "custom"]
    
    var body: some View {
        Form {
            Picker("Color", selection: $color) {
                ForEach(choices, id: \.self) {
                    Text($0)
                }
            }.pickerStyle(.segmented)
            if showCustomField {
                TextField("Color name", text: $customColor)
            }
        }
    }
}

  • Related