SwiftUI View和@FetchRequest谓词具有可以更改的变量 [英] SwiftUI View and @FetchRequest predicate with variable that can change
问题描述
我有一个视图,显示团队中使用@Fetchrequest和固定谓词开发人员过滤的消息。
I have a view showing messages in a team that are filtered using @Fetchrequest with a fixed predicate 'Developers'.
struct ChatView: View {
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
predicate: NSPredicate(format: "team.name == %@", "Developers"),
animation: .default) var messages: FetchedResults<Message>
@Environment(\.managedObjectContext)
var viewContext
var body: some View {
VStack {
List {
ForEach(messages, id: \.self) { message in
VStack(alignment: .leading, spacing: 0) {
Text(message.text ?? "Message text Error")
Text("Team \(message.team?.name ?? "Team Name Error")").font(.footnote)
}
}...
我想使此谓词动态化,以便在用户切换团队时显示该团队的消息。下面的代码给我以下错误
I want to make this predicate dynamic so that when the user switches team the messages of that team are shown. The code below gives me the following error
无法在属性初始值设定项中使用实例成员 teamName;属性初始值设定项在自我可用之前运行
Cannot use instance member 'teamName' within property initializer; property initializers run before 'self' is available
struct ChatView: View {
@Binding var teamName: String
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Message.createdAt, ascending: true)],
predicate: NSPredicate(format: "team.name == %@", teamName),
animation: .default) var messages: FetchedResults<Message>
@Environment(\.managedObjectContext)
var viewContext
...
我可以为此提供一些帮助,但到目前为止我还无法自行解决。
I can use some help with this, so far I'm not able to figure this out on my own.
推荐答案
遇到了同样的问题,布拉德·狄龙(Brad Dillon)的评论显示了解决方案:
had the same problem, and a comment of Brad Dillon showed the solution:
var predicate:String
var wordsRequest : FetchRequest<Word>
var words : FetchedResults<Word>{wordsRequest.wrappedValue}
init(predicate:String){
self.predicate = predicate
self.wordsRequest = FetchRequest(entity: Word.entity(), sortDescriptors: [], predicate:
NSPredicate(format: "%K == %@", #keyPath(Word.character),predicate))
}
在此示例中,您可以在初始化程序中修改谓词。
in this example, you can modify the predicate in the initializer.
这篇关于SwiftUI View和@FetchRequest谓词具有可以更改的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!