我在 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)
TL; 博士
您的变量currencyCode
与ForEach
. 迭代您的 中的代码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)
归档时间: |
|
查看次数: |
2622 次 |
最近记录: |