SwiftUI List rows loaded all at once

When using a simple SwiftUI List, the rows will be loaded lazy (not all at once) BUT: When having a ViewBuilder in place for each Row in the List all views are loaded at once (not lazy) Something like

 @ViewBuilder
    var content: some View {
        switch building.kind {
        case .condo:
            Text("Condo \(building.index)")
        case .house:
            Text("House \(building.index)")
        case .warehouse:
            Text("Warehouse \(building.index)")
        }
    }

Is this behavior correct and intended ?

Could you show the code where you build the List ?

sure. see the sample here. BuildingView will load all rows (i.e. 1000 instead of 17)


struct ContentView: View {
    @StateObject var store = Store()
    var body: some View {
        TabView {
            // Correct 
            houses.tabItem {
                Label("Houses", systemImage: "house")
            }
           // Wrong?
            buildings.tabItem {
                Label("Building", systemImage: "building")
            }
        }
    }

    var houses: some View {
        List {
            ForEach(store.houses) {house in
                HouseView(house: house)
            }
        }
    }

    var buildings: some View {
        List {
            ForEach(store.buildings) {building in
                BuildingView(building: building)
            }
        }
    }
}

struct HouseView: View {
    let house: House
    var body: some View {
        print(house.title) // Only visible will get loaded 
        return Text(house.title)
    }
}

struct BuildingView: View {
    let building: Building
    var body: some View {
        print(building.index) // loads all available items
        return content
    }

    @ViewBuilder
    var content: some View {
        switch building.kind {
        case .condo:
            Text("Condo \(building.index)")
        case .house:
            Text("House \(building.index)")
        case .warehouse:
            Text("Warehouse \(building.index)")
        }
    }
}

any idea here?

@tapework

sure. see the sample here. BuildingView will load all rows (i.e. 1000 instead of 17)

Do you have any logs for this and how are you debugging the behaviour?

If you include a print statement in the onAppear closure, you'll be able to debug when the view is added to the view hierarchy.

struct BuildingView: View {
    let building: Building
    
    var body: some View {
        content
            .onAppear {
                print(building.index)
            }
    }

    @ViewBuilder
    var content: some View {
        switch building.kind {
        case .condo:
            Text("Condo \(building.index)")
        case .house:
            Text("House \(building.index)")
        case .warehouse:
            Text("Warehouse \(building.index)")
        }
    }
}
SwiftUI List rows loaded all at once
 
 
Q