SwiftUI Picker 无法将数据从 Picker 传输到 Binding 变量

SwiftUI Picker unable to transfer data from Picker to Binding variable

希望您能从下面的代码中看到我试图实现的目标,但简单地说,我正在尝试更新绑定到我的选择器的 .selectedTown。点击的行将绑定到 .selectedTown,然后将更新文本 'Your selected town is: [.selectedTown]' 但是,所选行未绑定,文本仍为 'Your selected town is: '

struct ContentView: View {

struct Town: Identifiable {
    let name: String
    let id = UUID()
}

private var towns = [
    Town(name: "Bristol"),
    Town(name: "Oxford"),
    Town(name: "Portsmouth"),
    Town(name: "Newport"),
    Town(name: "Glasgow"),
]

@State private var selectedTown: String = ""

var body: some View {
    NavigationView {
        VStack {
            Form {
                Section {
                    Picker("", selection: $selectedTown) {
                        ForEach(towns, id: \.id) {
                            Text("\([=10=].name)")
                        }
                    }
                    .pickerStyle(.inline)
                    .labelsHidden()
                } header: {
                    Text("Random Towns")
                }
            }
            Text("Your selected town is: \(selectedTown)")
                .padding()
        }
        .navigationTitle("Random")
    }
}

}

希望这只是一个小修复,但我已经尝试了一天似乎找到了 solutino,但现在卡住了。如有任何帮助,我们将不胜感激,

西蒙

选择的类型应与选择的项目相同或使用 tag,如下所示

Picker("", selection: $selectedTown) {
    ForEach(towns, id: \.id) {
        Text("\([=10=].name)").tag([=10=].name)    // << here !!
    }
}

测试 Xcode 13.2 / iOS 15.2

类型不匹配。你的数组是 towns: [Town] 而你的 selectedTown: String

方案一是改变变量

@State private var selectedTown: Town = Town(name: "Sample")

选项 2 是添加标签

Text("\([=11=].name)").tag([=11=].name)

选项 3 是更改变量和标签

@State private var selectedTown: Town? = nil


Text("\([=12=].name)").tag([=12=] as? Town)

“最佳”选项取决于您 selectedTown 的用途。