Issue #621
Make subview that accepts FetchRequest
. Trigger search by setting property
struct SideView: View {
@Environment(\.managedObjectContext)
var context
@State var search: Search?
var body: some View {
VStack(alignment: .leading) {
SearchView(
onSearch: self.onSearch
)
InsideListView(fetchRequest: makeFetchRequest())
}
}
private func makeFetchRequest() -> FetchRequest<Book> {
let predicate: NSPredicate?
if let search = search {
let textPredicate = NSPredicate(format: "string CONTAINS[cd] %@", search.text)
let appPredicate = NSPredicate(format: "appName == %@", search.app)
let typePredicate = NSPredicate(format: "type == %@", search.type)
var predicates: [NSPredicate] = []
if search.text.count >= 3 {
predicates.append(textPredicate)
}
if search.app != Constants.all {
predicates.append(appPredicate)
}
if search.type != Constants.all {
predicates.append(typePredicate)
}
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
} else {
predicate = nil
}
return FetchRequest<Book>(
entity: Book.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Book.date, ascending: false)
],
predicate: predicate
)
}
private func onSearch(_ search: Search) {
if search.text.count < 3 && search.type != Constants.all && search.app != Constants.all {
self.search = nil
} else {
self.search = search
}
}
}
private struct InsideListView: View {
@Environment(\.managedObjectContext)
var context
var fetchRequest: FetchRequest<Book>
var body: some View {
List(items) {
ForEach
}
}
private var items: FetchedResults<Book> {
fetchRequest.wrappedValue
}
}