I have a SwiftData @Model class that has a var of Media.
enum Media: String, CaseIterable, Identifiable, Codable {
case dvd = "DVD"
case bluray = "Blu-ray"
case bluray4k = "Blu-ray 4k"
var id:String { self.rawValue }
}
In one of my views, I'm trying to show a Picker with the enum values, and then bind the @Model's field to the Picker's selection. I've been trying all kinds of things from suggesting I'm finding online. Here's a poorly pasted version of what my last attempt looks like (I'm sure I have the wrong number of closing curly brackets, but just ignore that):
struct DetailView: View {
@Binding var item:Item; // The @Model class.
@State private var selectedMedia:Media = .dvd;
var body:some View {
Picker("Media", selection:$selectedMedia) {
ForEach(Media.allCases, id:\.self) { media in
Text(media.rawValue);
}
}
.labelsHidden()
.onAppear() {
selectedMedia = item.media;
}
.onChange(of:selectedMedia) { oldValue, newValue in
item.media = selectedMedia;
}
}
}
What's a good way to make this work? Am I going to have to use a custom formatter of some type, bind the Picker to a string, and convert the selected value with the formatter?