SwiftUI - LazyVStack displaying more elements in view than required

2.2k views Asked by At

I've been following a youtube tutorial for using LazyVStacks. https://www.youtube.com/watch?v=o6D7mUXjSmI

When I run the same code as per the tutorial, the LazyVStack using Xcode Version 13.2.1 (13C100) on a iPhone 11 Pro Max (running iOS 15.2) prints out 83 statements, when only 42 rows are in view. As per the tutorial it should only print 42 statements to the console.

Is this an Xcode/iOS bug? I'm unable to download the latest Xcode as my Mac doesn't support macOS 12.0 to verify.

Video tutorial showing on 42 print statements in the console on iPhone 11 Pro Max: Video tutorial showing on 42 print statements in the console on iPhone 11 Pro Max

My code showing 83 print statements in the console on iPhone 11 Pro Max My code showing 83 print statements in the console on iPhone 11 Pro Max

import SwiftUI

struct SampleRow: View {
    let id: Int

    var body: some View {
        Text("Row \(id)")
    }
    
    init(id: Int) {
        print("Loading row \(id)")
        self.id = id
    }
}

struct ContentView: View {
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(1...1000, id: \.self, content: SampleRow.init)
            }
        }
    }
}
2

There are 2 answers

6
cole On

It's working fine in Xcode 13. I'm not sure why you need a LazyVStack, unless you're using some sort of grid. I slightly modified the code based on there's no much use for it here. It's printing all 1000.

print

enter image description here

import SwiftUI

struct SampleRow: View {
    let id: Int

    var body: some View {
        Text("Row \(id)")
    }
    

    init(id: Int) {
        print("Loading row \(id)")
        self.id = id
    }
}

struct ContentView: View {
    var body: some View {
        ScrollView {
            ForEach(1...1000, id: \.self) { index in
                SampleRow(id: index)
            }
        }
    }
}
1
Manfredi6 On

I got the exact same problem, I've got several views that render and fetch data dynamically upon reaching the bottom of the page but for some unknown reason, the same exact code is not working on a view where all the data are rendered at once.. I don't know if it's a bug in LazyVStack implementation or anything else but the behavior is ambiguous