swiftswiftuiswiftui-formswiftui-picker

Deselecting item from a picker SwiftUI


I use a form with a picker, and everything works fine (I am able to select an element from the picker), but I cannot deselect it. Does there exist a way to deselect an item from the picker? Thank you!

enter image description here

Picker(selection: $model.countries, label: Text("country")) {
                        ForEach(model.countries, id: \.self) { country in
                            Text(country!.name)
                                .tag(country)
                        }
                    }

Solution

  • First of, we can fix the selection. It should match the type of the tag. The tag is given Country, so to have a selection where nothing might be selected, we should use Country? as the selection type.

    It should looks like this:

    struct ContentView: View {
        
        @ObservedObject private var model = Model()
        @State private var selection: Country?
        
        var body: some View {
            NavigationView {
                Form {
                    Picker(selection: $selection, label: Text("country")) {
                        ForEach(model.countries, id: \.self) { country in
                            Text(country!.name)
                                .tag(country)
                        }
                    }
                    
                    Button("Clear") {
                        selection = nil
                    }
                }
            }
        }
    }
    

    You then just need to set the selection to nil, which is done in the button. You could set selection to nil by any action you want.