0

我尝试在分段选择器和滚轮选择器之间切换,但在单击时都没有注册选择。

NavigationView {
    Form {
        Picker(selection: self.$settings.senatorChoice, label: Text("Choose a senator")) {
            ForEach(0 ..< self.customSenators.count) {
                Text(self.customSenators[$0])
            }
        }.pickerStyle(WheelPickerStyle())
        .labelsHidden()
        .padding()
    }
}
4

3 回答 3

0

为每个选择器项目添加一个标签,以便它们是唯一的,例如

Text(self.customSenators[$0]).tag($0)
于 2020-06-13T22:04:35.533 回答
0

仔细检查这settings.senatorChoice是一个Int. 您的范围类型ForEach必须与您Picker的绑定类型相匹配。(有关更多信息,请参见此处)。

此外,您可能想要使用ForEach(self.customSenators.indices, id: \.self). 如果元素被添加到customSenators. (有关更多信息,请参见此处。)

于 2020-06-14T03:59:22.513 回答
0

以下测试代码在单击时注册选择。

struct Settings {
   var senatorChoice: Int = 0
}

struct ContentView: View {
@State private var settings = Settings()
@State private var customSenators = ["One","Two","Three"]

var body: some View {
    NavigationView {
        Form {
            Picker(selection: self.$settings.senatorChoice, label: Text("Choose a senator")) {
                ForEach(0 ..< customSenators.count) {
                    Text(self.customSenators[$0])
                }
            }.pickerStyle(SegmentedPickerStyle())
                .labelsHidden()
                .padding()
            Text("value: \(customSenators[settings.senatorChoice])")
        }
    }
}
}
于 2020-06-14T07:21:34.843 回答