传递核心数据FetchedResults< T>在SwiftUI中预览 [英] Passing Core Data FetchedResults<T> for previews in SwiftUI

查看:60
本文介绍了传递核心数据FetchedResults< T>在SwiftUI中预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父视图,该视图执行 @FetchRequest 并将 FetchedResults< T> 传递给子视图.一切正常,子视图能够通过 FetchedResults 进行解析.但是,我无法弄清楚如何设置数据以使孩子的 Preview 结构起作用.在 Preview 结构中设置一些常量数据的正确方法是什么,以便我可以实例化子视图并传递 FetchedResults< T> ?

I have a parent view which does a @FetchRequest and passes the FetchedResults<T> to a child view. Everything works, and the child view is able to parse through the FetchedResults. However, I can't figure out how to set up the data so that the child's Preview struct will work. What's the proper way to set up some constant data in Preview struct so that I can instantiate the child view and pass in FetchedResults<T>?

推荐答案

由于 FetchedResults< T> RandomAccessCollection ,而swift数组也是 RandomAccessCollection ,这是可能的解决方案.

As FetchedResults<T> is a RandomAccessCollection and swift array also is a RandomAccessCollection, here is possible solution.

通过Xcode 11.4/iOS 13.4测试

Tested with Xcode 11.4 / iOS 13.4

struct ContentView: View {
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: Person.entity(), sortDescriptors: [])
        var result: FetchedResults<Person>

    var body: some View {
        VStack(alignment: .leading) {
            Text("Persons").font(.title)
            PersonsView(results: result) // FetchedResults<Person> is a collection
        }
    }
}

// generalize PersonsView to depend just on collection
struct PersonsView<Results:RandomAccessCollection>: View where Results.Element == Person {
    let results: Results
    var body: some View {
        ForEach(results, id: \.self) { person in
            Text("Name: \(person.name ?? "<unknown>")")
        }
    }
}

struct ChildView_Previews: PreviewProvider {
    static var previews: some View {
        PersonsView(results: [Person()]) // << use regular array to test
    }
}

更新:已修复&Xcode 12/iSO 14的测试部分(由于上述PreviewProvider崩溃)

Update: fixed & tested part for Xcode 12 / iSO 14 (due to crash of above PreviewProvider)

看来实体现在应阅读&明确指定:

It appears entity now should be read & specified explicitly:

struct ChildView_Previews: PreviewProvider {
    static let entity = NSManagedObjectModel.mergedModel(from: nil)?.entitiesByName["Person"]

    static var previews: some View {
        let person = Person(entity: entity!, insertInto: nil)
        person.name = "Test Name"

        return PersonsView(results: [person])
    }
}

这篇关于传递核心数据FetchedResults&lt; T&gt;在SwiftUI中预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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