【问题标题】:Set default starting point on Picker在 Picker 上设置默认起点
【发布时间】:2020-08-18 16:53:40
【问题描述】:

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

这就是状态

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

}

【问题讨论】:

    标签: swift swiftui picker


    【解决方案1】:

    使选择成为可选,如下所示。使用 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))
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 当我尝试这个时,状态不再更新。我添加了Text("You selected: \(settings[Choioce!])") 以查看值的实时更改,但它没有像在将其变为可选之前那样更新。
    • 请查看更新,添加了修复和测试文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多