0

The following code creates a list of 20 view models(vm) and view displays only 6 at a time, but all 20 are created immediately. Any reason for that?

struct ContentView: View {
    @StateObject var vm = RMCharacterListResponseDownloadViewModel()
    
    let columns = Array(repeating: GridItem(.flexible(),spacing: 1, alignment: nil), count: 2)
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(vm.items, id: \.self) { item in
                    RMCharacterView(viewModel: item)
                }
            }
            .padding(1)
        }
    }
}

struct RMCharacterView: View {
    let viewModel: RMCharacterViewModel
    private let imageWidth = 110.0
    private let cellHeight = 330.0

    var body: some View {
        CacheAsyncImage(
            url: viewModel.characterImageURL
        ) { phase in
            switch phase {
            case .success(let image):
                VStack {
                    CharacterCard(characterImage: image)
                    CharacterDescriptionView(viewModel: viewModel)
                }
            case .failure(let error):
                ErrorView(error: error)
            case .empty:
                VStack {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle(tint: .red))
                    Spacer()
                }
            @unknown default:
                // AsyncImagePhase is not marked as @frozen.
                // We need to support new cases in the future.
                Image(systemName: "questionmark")
            }
        }
    }
}

I expected only 6 cells would be created and each associated image would be downloaded, but all were created immediately.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Craig
  • 11
  • 1
  • This needs a [mre] – jnpdx Jun 11 '23 at 21:51
  • 2
    I seem to remember in [Demystify SwiftUI performance](https://developer.apple.com/videos/play/wwdc2023/10160/?time=1225) that the value you are using in a ForEach should be `Identifiable`. "Note that this approach to view counts is only relevant in the context of ForEach within List and Table because those components gather their identifiers up front." You are using `\.self`. – Yrb Jun 11 '23 at 21:51

0 Answers0