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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…