在 PreviewProvider 中模拟 EvironmentObject
Mocking an EvironmentObject in PreviewProvider
我正在使用 EnvironmentObject 作为我的数据源来使用 SwiftUI。我想知道如何在使用 PreviewProvider 时模拟它。
示例代码如下:
struct ListView: View {
@State private var query: String = "Swift"
@EnvironmentObject var listData: ListData
var body: some View {
NavigationView {
List(listData.items) { item in
ListItemCell(item: item)
}
}.onAppear(perform: fetch)
}
private func fetch() {
listData.fetch()
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
How do I mock this?
// ListView(listData: EnvironmentObject<ListData>)
}
}
class ListData: BindableObject {
var items: [ListItem] = [] {
didSet {
didChange.send(self)
}
}
var didChange = PassthroughSubject<ListData, Never>()
func fetch() {
// async call that updates my items
self?.items = someNetworkResponse
}
}
这在我的 ListData 中运行良好 class:
#if DEBUG
let mockedListView = ListView().environmentObject(ListData())
#endif
我正在使用 EnvironmentObject 作为我的数据源来使用 SwiftUI。我想知道如何在使用 PreviewProvider 时模拟它。
示例代码如下:
struct ListView: View {
@State private var query: String = "Swift"
@EnvironmentObject var listData: ListData
var body: some View {
NavigationView {
List(listData.items) { item in
ListItemCell(item: item)
}
}.onAppear(perform: fetch)
}
private func fetch() {
listData.fetch()
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
How do I mock this?
// ListView(listData: EnvironmentObject<ListData>)
}
}
class ListData: BindableObject {
var items: [ListItem] = [] {
didSet {
didChange.send(self)
}
}
var didChange = PassthroughSubject<ListData, Never>()
func fetch() {
// async call that updates my items
self?.items = someNetworkResponse
}
}
这在我的 ListData 中运行良好 class:
#if DEBUG
let mockedListView = ListView().environmentObject(ListData())
#endif