I have several Pickers in a SwiftUI App where the Picker items are stored in Core Data. Each Picker item is only a title: String and a comment: String.
The App has a List and DetailView format, with the Picker in the DetailView. I use an @State var to indicate whether editing is in process. If isEditing is false, a text field shows the stored choice. If isEditing is true, the Picker is shown. This all works well except that setting isEditing to true displays the picker with item 0 from the data backing. The real value is still in Core Data but it looks to the user that the choice has been overwritten.
I created a custom Binding to set the user selections:
var spinner1Binding: Binding<Int> {
Binding(
get: { self.selectionIndex1 },
set: {
self.selectionIndex1 = $0
self.picker1Text = picker1ListVM.picker1Items[self.selectionIndex1].picker1Title
patientDetailVM.pubSpinner1 = picker1ListVM.picker1Items[self.selectionIndex1].picker1Title
})}
The view model picker1Items is an array of Picker1Model
struct Picker1Model: Identifiable {
let picker1Item: Picker1Item
var id: NSManagedObjectID {
return picker1Item.objectID
}
var picker1Title: String {
return picker1Item.title ?? "No Picker 1 Title"
}
var picker1Comment: String {
return picker1Item.comment ?? "No Picker 1 Comment"
}
}//picker 1 model
This is the code in DetailView. I only added the second text to illustrate that the real value is still the published value:
VStack {
Text(appSpinner1Title + ":")
.modifier(LabelTextSetup())
//Remove this when problem solved
Text(isEditing ? "Current: \(patientDetailVM.pubSpinner1)" : "")
.modifier(LabelTextSetup())
}
Spacer()
if isEditing {
Picker(selection: spinner1Binding, label : Text("Picker One Choice")) {
ForEach(picker1ListVM.picker1Items.indices, id: \.self) { index in
Text(picker1ListVM.picker1Items[index].picker1Title).tag(index)
}//for
}//picker
} else {
Text(patientDetailVM.pubSpinner1)
.modifier(LabelTextSetup())
}
When not editing it looks like this:
When editing it looks like this. Obviously, what I want is for the picker to display "Urgently Ortho" in this scenario.
Seems like this should be easy, but I have not been successful.
Any guidance would be appreciated. Xcode 13.2.1 iOS 15

