问题描述
如何在选择器内将起始值设置为文本“请选择一个”。当前,它默认为数组中的第一选择。
这是状态
@State var Choioce = 0
这是选择器
var settings = ["ch1","ch2","ch3"]
Picker("Options",selection: $Choioce) {
Text("Please Select One")
ForEach(0 ..< settings.count) { index in
Text(self.settings[index])
.tag(index)
}
}
解决方法
使选择为可选,如下所示。经过Xcode 12 / iOS 14的测试
struct ContentView: View {
@State var Choioce: Int? // << here !!
var settings = ["ch1","ch2","ch3"]
var body: some View {
VStack {
Text("Selection: \(Choioce == nil ? "<none>" : settings[Choioce!])")
Picker("Options",selection: $Choioce) {
Text("Please Select One").tag(Optional<Int>.none)
ForEach(0 ..< settings.count) { index in
Text(self.settings[index])
.tag(Optional(index))
}
}
}
}
}