Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Toggle view on specific picker value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading