Suppose you have a view:
struct Library: View {
@State var books = []
var body: some View {
VStack {
...
Button("add Book") {
....
}
}
}
Such that Library
view holds a Book
array that gets populated internally via a button that opens a modal – or something alike.
How can I use #Peview
s to preview Library
with a pre-populated collection? Suppose I have a static
books – dummy – array in my code just for that; still, what's the best way to use that to preview the Library
view?
This is really a more idiomatic way:
struct BookProvider: PreviewModifier {
static func makeSharedContext() async -> [Book] {
let url = Bundle.main.url(forResource: "Curs confirmare RO", withExtension: "pdf")!
return await withTaskGroup { tg in
for _ in 0..<10 {
tg.addTask {
return await createBook(for: url, of: CGSize(width: 200, height: 200), scale: 4.0)
}
}
var books: [Book] = []
for await result in tg {
books.append(result)
}
return books
}
}
func body(content: Content, context: [Book]) -> some View {
ContentView(books: context)
}
}
#Preview(traits: .modifier(BookProvider())) {
ContentView()
}