Search code examples
swiftuiscrollview

Using ScrollView is not showing my List data


In below code I want to implement a ScrollView as I don't know how many items will be in my List. Problem is that nothing of the list is shown when running. If I remove the ScrollView my List becomes visible. What am I missing here:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            ScrollView() {
                VStack(alignment: .leading) {
                    List {
                        ForEach(1..<10) { i in
                            Text("\(i) SomeItem")
                        }
                    }
                }
            }
            .navigationTitle("ScrollViewTest")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Using Xcode 14.2, no extensions.


Solution

  • You don't need to use ScrollView or a VStack with a List, since List already loads its views lazily. You can see how the "CustomView" is loaded in the example below.

    struct ScrollViewTest: View {
        
        var body: some View {
            NavigationView {
                List {
                    ForEach(1..<10000) { i in
                        CustomView(number: i)
                        
                    }
                }
                .navigationTitle("ScrollViewTest")
            }
        }
    }
    
    struct CustomView: View {
        
        init(number: Int) {
            self.number = number
            print("\(number) is loaded") // <- check how the views are loaded lazily while scrolling in the list
        }
        
        let number: Int
        
        var body: some View {
            Text("\(number) SomeItem")
        }
    }