swiftuiswiftui-layout

Does a LazyVStack remain "lazy" if it's inside a VStack?


Let's consider a list of 100 posts. According to Apple, if I layout them inside a LazyVStack:

the stack view doesn’t create items until it needs to render them onscreen.

What if I embed that LazyVStack inside a VStack? Does it still load the views "as needed"?


Solution

  • struct MyView: View {
        init() {
            print("init...")
        }
        
        var body: some View {
            Text("test")
        }
    }
    
    struct ContentView: View {
        var body: some View {
            ScrollView {
                VStack {
                    LazyVStack {
                        ForEach.init(0..<100) { int in
                            MyView()
                        }
                    }
                }
            }
        }
    }
    

    Running the above code, as we scroll we can see more MyViews are init'd (by viewing the print statements in the console), so it seems like a LazyVStack in a VStack does indeed create it's content lazily. We can see the same is true when removing the VStack as well.