Getting size of VStack embedded in scroll view

Hello, I have been playing around with preference keys and geometry readers but I can't figure out a way to actually get the real size of a scrollview or vstack inside a scroll view. I have 2 different approaches and they both semi work, the problem with them is that when I scroll through the scroll view the size fluctuates. For example if the size of the vstack in the scroll view is 5000, then the size I get from my methods will fluctuate between 4200-5900 as I scroll through the view. Im not sure why this is, can anyone show me a solid way to get the height of a vstack inside a scrollview.

               ScrollView {
                    ChildSizeReader(size: $scrollViewSize) {
                        LazyVStack { 
                            ForEach(viewModel.new) { I in
                                    someView(i)
                                }
                            }
                        }
                    }
                }

struct ChildSizeReader<Content: View>: View {
@Binding var size: CGSize
let content: () -> Content
var body: some View {
ZStack {
content().background(
GeometryReader { proxy in
Color.clear.preference(
key: SizePreferenceKey.self,
value: proxy.size
}
}
}
}
.onPreferenceChange(SizePreferenceKey.self) { preferences in
self.size = preferences
}
}
}

struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value = .zero

static func reduce(value _: inout Value, nextValue: () -> Value) {
  _ = nextValue()
}

}

1 Like