从选择器 SwiftUI 中取消选择项目

Joh*_*nas 5 swift swiftui swiftui-form swiftui-picker

我使用带有选择器的表单,一切正常(我可以从选择器中选择一个元素),但我无法取消选择它。是否存在从选择器中取消选择项目的方法?谢谢你!

在此输入图像描述

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

Asp*_*eri 9

要取消选择,我们需要选择器值的可选存储,因此这里是可能方法的演示。

使用 Xcode 12.1 / iOS 14.1 进行测试

演示

struct ContentView: View {
    @State private var value: Int?
    var body: some View {
        NavigationView {
            Form {
                let selected = Binding(
                    get: { self.value },
                    set: { self.value = $0 == self.value ? nil : $0 }
                )
                Picker("Select", selection: selected) {
                    ForEach(0...9, id: \.self) {
                        Text("\($0)").tag(Optional($0))
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*e_E 1

首先,我们可以修复选择。它应该与标签的类型匹配。标签是给定的Country,因此要进行可能不选择任何内容的选择,我们应该使用Country?类型selection

它应该看起来像这样:

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
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您只需将 设置selectionnil,这是在按钮中完成的。您可以通过任何您想要的操作来selection设置。nil