dictionary - 将 SwiftUI Picker 绑定(bind)到字典中保存的值

标签 dictionary binding swiftui

以下代码编译并运行,但只有绑定(bind)到数组中的值的选择器才能工作。那些在字典里的人失败了。知道为什么会这样吗?

import SwiftUI

struct ContentView: View {

    private var options : [String] = ["Bonjour", "Hello", "Hola"]

    @State private var choicesHeldInArray = [0, 2]
    @State private var choicesHeldInDict: [String: Int] = ["C3": 2, "C4":1]

    var body: some View {

        VStack {

            Picker(selection: $choicesHeldInArray[0], label: Text("Choice 1")) {
                ForEach(0 ..< options.count) {
                    Text(self.options[$0])
                }
            }

            Picker(selection: $choicesHeldInArray[1], label: Text("Choice 2")) {
                ForEach(0 ..< options.count) {
                    Text(self.options[$0])
                }
            }

            Picker(selection: $choicesHeldInDict["C3"], label: Text("Choice 3")) {
                ForEach(0 ..< options.count) {
                    Text(self.options[$0])
                }
            }

            Picker(selection: $choicesHeldInDict["C4"], label: Text("Choice 4")) {
                ForEach(0 ..< options.count) {
                    Text(self.options[$0])
                }
            }
        }
    }
}

最佳答案

Could the answer be something because of this?

简而言之 您不能使用 ForEach 因为:

  • 它会观察集合并监控运动。使用无序字典是不可能的。

关于dictionary - 将 SwiftUI Picker 绑定(bind)到字典中保存的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60853197/

相关文章:

python - 将 .txt 文件处理成字典 (Python v2.7)

python - 将列表或字典打印到列中

python - 循环遍历包含字典的嵌套列表

WPF 条件绑定(bind)。 Button.IsEnabled 到 SelectedIndex >= 0

c# - 将标签绑定(bind)到变量

swift - 如何在 TextField 中将占位符文本居中

swift - 更新 UIHostingConfiguration 中的@FocusState

button - SwiftUI-按钮-如何将函数请求传递给父级

c++ - 为什么 map::find 会找到它不应该存在的东西?

jQuery 绑定(bind)事件触发事件