在选择器上设置默认起点

问题描述

如何在选择器内将起始值设置为文本“请选择一个”。当前,它默认为数组中的第一选择。

这是状态

@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的测试

demo

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))
                }
            }
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...