问题描述
我正在使用一种形式的分段选择器来回答简单的“是”和“否”问题。可以将分段选择器的初始状态设置为nil,以便在出现时不会突出显示/选择是或否吗?
@State private var equipmentCheck = 0
private var answers = ["Yes","No"]
var body: some View {
NavigationView {
Form {
Section(header: Text("Questions")) {
Text("Have the plant and equipment been checked?")
Picker("",selection: $equipmentCheck) {
ForEach(0 ..< answers.count,id: \.self) {
Text("\(self.answers[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
}
}
}
}
解决方法
似乎,如果将选定的值设置为不在分段控件中的索引,则不会突出显示任何值。
例如:
@State private var equipmentCheck = -1
有效。
我正在寻找可以确保可以正常工作但没有找到工作的文档。
UIKit UISegmentedControl
的{{3}}的文档说将值设置为-1以删除选择,因此在这里也这样做是合理的。
这是一种可能的方法。经过测试并与Xcode 11.4 / iOS 13.4配合使用
@State private var equipmentCheck: Int? // << here !!
private var answers = ["Yes","No"]
var body: some View {
NavigationView {
Form {
Section(header: Text("Questions")) {
Text("Have the plant and equipment been checked?")
Picker("",selection: $equipmentCheck) {
ForEach(0 ..< answers.count,id: \.self) {
Text("\(self.answers[$0])")
.tag(Optional($0)) // << here !!
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
}
}
}
}