简体   繁体   中英

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. 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. My code looks like this ( explorerViewModel.currencies is a Set of Currency):

@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 :

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.

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

worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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