简体   繁体   English

SwiftUI 选择器未选择默认值且对象不工作

[英]SwiftUI Picker with unselected default and objects not working

I am using a Picker to select a Currency, which is an Identifiable Class based on a Core Data Entity.我正在使用选择器来选择 select 货币,它是基于核心数据实体的可识别 Class。 I thereby would want that there is no initial selection in the picker.因此,我希望选择器中没有初始选择。 However, somehow that is not working, and I can't select anything in the picker.但是,不知何故,这不起作用,我不能 select 选择器中的任何东西。 My code looks like this ( explorerViewModel.currencies is a Set of Currency):我的代码如下所示( explorerViewModel.currencies是一组货币):

@State private var selectedCurrency: Currency?

var body: some View {
   Form {
      Picker("Currency", selection: $selectedCurrency) {
         ForEach(explorerViewModel.currencies) { currency in
            Text(currency.name)
         }
      }
}

Any help what is wrong here?任何帮助这里有什么问题?

In case required, that is the code for the explorerViewModel :如果需要,这是explorerViewModel的代码:

class ExplorerViewModel: ObservableObject {

private let moc: NSManagedObjectContext

@Published var currencies: [Currency]

init() {
    self.moc = PersistenceController.shared.container.viewContext
    currencies = (try? moc.fetch(NSFetchRequest<Currency>(entityName : "Currency"))) ?? []
}

} }

I actuallt found the issue: I had to append a tag to make the currency optional.我实际上发现了问题:我必须给 append 一个标签才能使货币可选。

Text(currency.name).tag(currency as Currency?)

worked.工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM