我的 SwiftUI 项目中有这段代码运行良好
struct ContentView: View {
@State private var selectedCountry: Country?
@State private var showSetting = false
@FetchRequest(entity: Country.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Country.cntryName, ascending: true)]
) var countries: FetchedResults<Country>
var body: some View {
NavigationView {
VStack {
Form {
Picker("Pick a country", selection: $selectedCountry) {
ForEach(countries, id: \Country.cntryName) { country in
Text(country.cntryName ?? "Error").tag(country as Country?)
}
}
if selectedCountry != nil {
DetailView(cntryName: (selectedCountry?.cntryName!)!)
}
}
}
.navigationBarTitle("UNECE Data")
.navigationBarItems(trailing: Button("Settings", action: {
self.showSetting.toggle()
}))
}
.sheet(isPresented: $showSetting) {
SettingsView(showSetting: self.$showSetting)
}
}
}
但是,当 SettingsView 关闭时,我需要动态调用 FetchRequest 结束重新加载 Picker 视图。可能我应该使用@ObservableObject,但是如何在 Picker 视图 ForEach 中放置获取请求并使用结果?感谢您的提示。