SwiftUI 视图和带有可以更改的变量的 @FetchRequest 谓词 [英] SwiftUI View and @FetchRequest predicate with variable that can change

查看:19
本文介绍了SwiftUI 视图和带有可以更改的变量的 @FetchRequest 谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图显示团队中的消息,这些消息使用带有固定谓词开发人员"的@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";属性初始值设定项在 'self' 可用之前运行

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 视图和带有可以更改的变量的 @FetchRequest 谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆