I have created a very simple test in SwiftUI:
Pokemon
struct Pokemon: Identifiable {
let id: Int
let name: String
}
PokemonList
struct PokemonList: View {
@State private var pokemonList: [Pokemon] = []
var body: some View {
List(pokemonList) {
PokemonRow(pokemon: $0)
}
.listStyle(PlainListStyle())
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// Here I fill Pokemon list from API
}
}
}
init(_ pokemonList: [Pokemon] = []) {
self.pokemonList = pokemonList
}
}
#if DEBUG
struct PokemonList_Previews: PreviewProvider {
static var previews: some View {
PokemonList([
Pokemon(id: 1, name: "Bulbasaur"),
Pokemon(id: 25, name: "Pikachu"),
Pokemon(id: 150, name: "Mewtwo")
])
}
}
#endif
PokemonRow
struct PokemonRow: View {
var pokemon: Pokemon
var body: some View {
HStack(alignment: .center) {
Text("#\(pokemon.id)")
Text(pokemon.name)
}
.padding()
.frame(height: 50)
}
}
#if DEBUG
struct PokemonRow_Previews: PreviewProvider {
static var previews: some View {
PokemonRow(pokemon: Pokemon(id: 25, name: "Pikachu"))
}
}
#endif
The PokemonRow
preview works fine, and the API call too (the list is correctly filled after the view appears), but for some reason the PokemonList
preview always displays empty content. Why is that?
Thank you for your help