[英]Dynamically filtering @FetchRequest with SwiftUI using Bool - show true, false or both
I have a list in SwiftUI in (ListView) that pulls data from Core Data.我在 (ListView) 中的 SwiftUI 中有一个列表,可以从 Core Data 中提取数据。 I would like to filter it dynamically.我想动态过滤它。 I have a fetchRequest like this:我有一个这样的 fetchRequest:
init(filter: Bool) {
fetchRequest = FetchRequest<Transaction>(entity: Transaction.entity(), sortDescriptors: [], predicate: NSPredicate(format: "income = %d", filter))
}
Transaction is a Core Data Entity with an Attribute income (Bool).交易是具有属性收入(布尔)的核心数据实体。
In ContentView I am calling ListView like this:在 ContentView 中,我像这样调用 ListView:
ListView(filter: incomeTypeFilter)
And I have 3 buttons to change filter (true or false which stands for true=income, false=expenses):我有 3 个按钮来更改过滤器(真或假,代表真=收入,假=费用):
Button("Show income") {
self.incomeTypeFilter = true
}
Button("Show expenses") {
self.incomeTypeFilter = false
}
Button("Show ALL") {
// I don't know how to show ALL items in the list. Both true and false.
}
Buttons to show income and expenses work.显示收入和支出的按钮工作。 They change self.incomeTypeFilter to be true or false.他们将 self.incomeTypeFilter 更改为 true 或 false。 But how to change predicate to show ALL items?但是如何更改谓词以显示所有项目? Both true and false?既真又假?
Ps My code is based on this tutorial: Dynamically filtering @FetchRequest with SwiftUI Ps 我的代码基于本教程: Dynamically filtering @FetchRequest with SwiftUI
Use one of two fetch requests, one with a predicate and one without and determine which one to use by letting the parameter be optional使用两个 fetch 请求之一,一个有谓词,一个没有,并通过让参数是可选的来确定使用哪一个
init(filter: Bool?) {
if let filter = filter {
fetchRequest = FetchRequest<Transaction>(entity: Transaction.entity(), sortDescriptors: [], predicate: NSPredicate(format: "income = %d", filter))
} else {
fetchRequest = FetchRequest<Transaction>(entity: Transaction.entity(), sortDescriptors: [])
}
}
So all would correspond to calling the init with nil所以所有都对应于用 nil 调用 init
EDIT:编辑:
And later: Make incomeTypeFilter var in ContentView optional:后来:使 ContentView 中的incomeTypeFilter var 可选:
@State var incomeTypeFilter :Bool? = true
And make SHOW ALL button like this:并像这样制作 SHOW ALL 按钮:
Button("Show ALL") {
self.incomeTypeFilter = nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.