0

I want to calculate how much I can scroll from the height of the entire ScrollView to the bottom of the ScrollView, but I can't get the height of the entire ScrollView. If there is any way to do this, please let me know.

scrollView.contentSize.height scrollView.frame.height

The top two are the values you want to get

var body: some View {
    ScrollView {
        ForEach(0..<100, id: \.self) { number in
            Text("\(number)")
        }
    }
}
zlatan
  • 9
  • 3

1 Answers1

0

Here is a solution based on ViewHeightKey preference key from my answer in How to make a SwiftUI List scroll automatically?

var body: some View {
    ScrollView {
        VStack {
            ForEach(0..<100, id: \.self) { number in
                Text("\(number)")
            }
        }
        .modifier(ViewHeightKey())   // calculate here !!
    }
    .onPreferenceChange(ViewHeightKey.self) { // read here !!
        print("Content height: \($0)")
    }
    .background(GeometryReader { gp -> Color in
        let frame = gp.frame(in: .local)
        print("ScrollView height: \(frame.size.height)")
        return Color.clear
    })
}
Asperi
  • 228,894
  • 20
  • 464
  • 690