TL;DR
您的currencyCode
变量与ForEach
中每个元素的ID类型不匹配。要么在ForEach
中迭代代码,要么将索引传递给您的Picker
。
以下是三个等效的示例。请注意,传递给Picker
的@State
变量始终与ForEach
迭代的元素ID相匹配:
还要注意,我选择了一个默认值作为@State
变量,该值不在数组中(“”,-1,UUID()),因此在加载表单时不会显示任何内容。如果您想要一个默认选项,请将其设置为@State
变量的默认值。
示例1:迭代代码(即字符串)
struct ContentView: View {
@State private var currencyCode: String = ""
var codes: [String] = ["EUR", "GBP", "USD"]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $currencyCode, label: Text("Currency")) {
// ID is a String ----v
ForEach(codes, id: \.self) { (string: String) in
Text(string)
}
}
}
}
}
}
}
示例2:按索引(即Int)进行迭代
struct ContentView: View {
@State private var selectedIndex: Int = -1
var codes: [String] = ["EUR", "GBP", "USD"]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedIndex, label: Text("Currency")) {
// ID is an Int --------------v
ForEach(codes.indices, id: \.self) { (index: Int) in
Text(self.codes[index])
}
}
}
}
}
}
}
示例3:按其ID类型(即UUID)迭代可识别的结构
struct Code: Identifiable {
var id = UUID()
var value: String
init(_ value: String) {
self.value = value
}
}
struct ContentView: View {
@State private var selectedUUID = UUID()
var codes = [Code("EUR"), Code("GBP"), Code("USD")]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedUUID, label: Text("Currency")) {
// ID is a UUID, because Code conforms to Identifiable
ForEach(self.codes) { (code: Code) in
Text(code.value)
}
}
}
}
}
}
}
Picker
因为一个bug而无法正常工作。该问题已在XCode 11.2 / iOS 13.2 beta版本中得到修复。 - John M.codes
或currencyCode
的声明。我怀疑问题在于你绑定的类型与你在选择器上设置的标记不同(在你的情况下是Int)。struct ContentView: View {
let codes = Array(CurrencyCode.allCases)
@State private var currencyCode: CurrencyCode?
var body: some View {
NavigationView {
Form {
Section {
Picker("Currency",
selection: $currencyCode) {
ForEach(codes, id: \.rawValue) {
Text($0.rawValue).tag(Optional<CurrencyCode>.some($0))
}
}
}
}
}
}
}
enum CurrencyCode: String, CaseIterable {
case eur = "EUR"
case gbp = "GBP"
case usd = "USD"
}
currencyCode
的初始值是什么? - Yonat