I have a Core Data app which I am trying to create pickers in order to help the users filter the core data objects to more quickly find the object they are actually looking for. Two of the filters are based on a core data relationship and those I have working because they are always unique values in the related core data entity. The other two attributes (year collected and seed source) are based on user entered values, and so there could be 1 to n unique values. If I use the fetch request to populate the picker, I get all of the values not just the unique ones, which really makes it useless as a filter.
I am extremely new to SwiftUI and to asking for help in a forum so please let me know if I need to provide different/better information.
struct CrossListView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: [
SortDescriptor(\.name)
]) var dahlias: FetchedResults<Dahlia>
@FetchRequest(sortDescriptors: [
SortDescriptor(\.name)
], predicate: NSPredicate(format: "name == %@", "Open Pollination")) var openPollination: FetchedResults<Dahlia>
private var activeDahlias: [Dahlia] {
return dahlias.filter { r in
return r.archive == false && r.parent == true
}
}
@State public var seedParent: Dahlia?
@State public var pollenParent: Dahlia?
@FetchRequest(sortDescriptors: [
SortDescriptor(\.yearCollected)
]) var crosses: FetchedResults<Cross>
@State private var seedFilter = ""
@State private var pollenFilter = ""
@State private var yearFilter = ""
@State private var seedSourceFilter = ""
var body: some View {
NavigationView{
VStack{
Form{
if showingFilterSection == false {
Section(header:
Button {
showingFilterSection.toggle()
} label: {
HStack {
Image(systemName: "plus.rectangle")
Text("SHOW FILTERS")
}
})
{
EmptyView()
}
} else {
Section(header:
Button {
showingFilterSection.toggle()
seedFilter = ""
pollenFilter = ""
yearFilter = ""
seedSourceFilter = ""
} label: {
HStack {
Image(systemName: "minus.rectangle")
Text("HIDE FILTERS")
}
})
{
Picker("Seed Parent", selection: $seedFilter) {
Text("All").tag("All")
ForEach(activeDahlias.sorted(), id: \.self) { (activeDahlias: Dahlia) in
Text(activeDahlias.wrappedName).tag(activeDahlias.wrappedName as String)
}
}
Picker("Pollen Parent", selection: $pollenFilter) {
Text("All").tag("All")
ForEach(activeDahlias.sorted(), id: \.self) { (activeDahlias: Dahlia) in
Text(activeDahlias.wrappedName).tag(activeDahlias.wrappedName as String)
}
}
Picker("Year Collected", selection: $yearFilter) {
Text("All").tag("All")
ForEach(crosses, id: \.self) { (cross: Cross) in
Text(String(cross.yearCollected)).tag(cross.yearCollected)
}
}
Picker("Seed Source", selection: $seedSourceFilter) {
Text("All").tag("All")
ForEach(activeDahlias.sorted(), id: \.self) { (activeDahlias: Dahlia) in
Text(activeDahlias.wrappedName).tag(activeDahlias.wrappedName as String)
}
}
}
}
List{
ForEach(crosses) {cross in
NavigationLink {
// and then here is where the list generates