问题描述
我使用带有选择器的表单,一切正常(我可以从选择器中选择一个元素),但我无法取消选择它.是否存在从选择器中取消选择项目的方法?谢谢!
Picker(selection: $model.countries, label: Text("country")) {ForEach(model.countries, id: \.self) { country in文本(国家!.名称).tag(国家)}}
首先,我们可以修复选择.它应该与标签的类型相匹配.标签被赋予 Country
,所以要选择一个什么都不选的选项,我们应该使用 Country?
作为 selection
类型.>
它应该是这样的:
struct ContentView: 查看 {@ObservedObject 私有变量模型 = Model()@State 私有变量选择:国家?var主体:一些视图{导航视图{形式 {Picker(selection: $selection, label: Text("country")) {ForEach(model.countries, id: \.self) { country in文本(国家!.名称).tag(国家)}}按钮(清除"){选择 = 无}}}}}
然后您只需要将selection
设置为nil
,这在按钮中完成.您可以通过任何您想要的操作将 selection
设置为 nil
.
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!
Picker(selection: $model.countries, label: Text("country")) {
ForEach(model.countries, id: \.self) { country in
Text(country!.name)
.tag(country)
}
}
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.
这篇关于从选择器 SwiftUI 中取消选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!