我正在尝试在SwiftUI(XCode 11.3.1)中使用具有动态数据的多个选择器。该应用程序有时会在模拟器和运行iOS 13.3.1的实际设备上崩溃,有时会冻结或在选择器中显示错误的数据。我尝试了这个问题答案中的建议,但没有成功。我做错了什么?
import SwiftUI
struct DbItem : Identifiable {
var id: Int
var name: String
}
final class DbStore : ObservableObject {
let countries: [DbItem] = [DbItem(id: 0, name: "USA"), DbItem(id: 1, name: "France")]
let citymap:[Int:[DbItem]] = [0:[DbItem(id: 10, name: "New York"), DbItem(id: 11, name: "Los Angeles"), DbItem(id: 12, name: "Dallas"), DbItem(id: 13, name: "Chicago")], 1:[DbItem(id: 20, name: "Paris"), DbItem(id: 21, name: "Nice"), DbItem(id: 22, name: "Lille")]]
@Published var cities = [DbItem]()
@Published var country : Int = -1 {
willSet {
if newValue >= 0 {
self.id = UUID()
DispatchQueue.main.async { [newValue] in
self.cities = self.citymap[newValue]!
}
}
}
}
@Published var city : Int = -1 {
didSet {
}
}
}
struct ContentView: View {
@EnvironmentObject private var store: DbStore
var body: some View {
NavigationView {
Form {
VStack {
Picker(selection: $store.country,
label: Text("Country: ")
) {
ForEach(store.countries) { country in
Text(country.name)
}
}
Picker(selection: $store.city,
label: Text("City: ")
) {
ForEach(store.cities) { city in
Text(city.name)
}
}
.disabled(store.country < 0)
}
}
}
}
}