如何将起始值设置为选择器内的文本“请选择一个”。目前它默认为数组中的第一个选择。
这就是状态
@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))
}
}
}
}
}
将您的选择绑定数据类型更改为字符串
@State var choice: String = "Please Select One"
然后对选择器逻辑进行细微更改
var settings = ["ch1", "ch2", "ch3"]
Picker("Options", selection: $choice) {
ForEach(settings, id: \.self) {
Text($0)
}
}
你就完成了。