表单中的 SwiftUI 选择器不显示复选标记

gpi*_*ler 5 ios swiftui

我在 Form 中嵌入了一个 Picker,但是我无法让它工作,因为它在表单中显示了一个复选标记和选定的值。

NavigationView {
    Form {
        Section {
                Picker(selection: $currencyCode, label: Text("Currency")) {
                    ForEach(0 ..< codes.count) {
                        Text(self.codes[$0]).tag($0)
                    }
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

没有复选标记和没有选择的值

Joh*_* M. 7

TL; 博士

您的变量currencyCodeForEach. 迭代您的 中的代码ForEach,或者传递您Picker的索引。

下面是三个等效的例子。请注意,@State传递给的变量Picker始终与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)
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例 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])
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例 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)
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @GeoffHom 如果您使用的是 XCode 11.1 / iOS 13.1.2,“Picker”会被错误破坏。它已在 XCode 11.2 / iOS 13.2 beta 中修复。 (2认同)