如何在 SwiftUI 中使用带有新的可搜索修饰符的@FetchRequest? [英] How to use a @FetchRequest with the new searchable modifier in SwiftUI?

查看:33
本文介绍了如何在 SwiftUI 中使用带有新的可搜索修饰符的@FetchRequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将新的 searable@FetchRequest 结合使用?

is it somehow possible to use the new searable in combination with a @FetchRequest?

我有这样的代码:

struct FooListView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Foo.name, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Foo>

    @State var searchText = ""

    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    NavigationLink(destination: FooView(Foo: item)) {
                        Text(item.wrappedName)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .searchable(text: $searchText)
            .navigationTitle("Foos")
        }
    }
}

在这个简单的例子中,我想使用 searchText 来跟踪我的 FetchedResults.

In this simple example I would like to use the searchText to folter my FetchedResults.

推荐答案

WWDC 2021 为 Swift 带来核心数据并发性,SwiftUI 在 21:33 左右有一个很好的例子

WWDC 2021 Bring Core Data Concurrency to Swift and SwiftUI has a great example of this right around minute 21:33

https://developer.apple.com/wwdc21/10017

struct ContentView: View {
    @FetchRequest(sortDescriptors: [SortDescriptor(\Quake.time, order: .reverse)])
    private var quakes: FetchedResults<Quake>

    @State private var searchText = ""
    var query: Binding<String> {
        Binding {
            searchText
        } set: { newValue in
            searchText = newValue
            quakes.nsPredicate = newValue.isEmpty
                           ? nil
                           : NSPredicate(format: "place CONTAINS %@", newValue)
        }
    }

    var body: some View {
        List(quakes) { quake in
            QuakeRow(quake: quake)
        }
        .searchable(text: query)
    }
}

这篇关于如何在 SwiftUI 中使用带有新的可搜索修饰符的@FetchRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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