6

I want to determine the height of the content inside my (vertical) ScrollView.

ScrollView {  
    //My Content
}

Is this possible? I've tried a few things but nothing seems to work.

Unfortunately, using simply the GeometryReader isn't working, since it returns a value of 10 no matter what content is inside the ScrollView

Thanks!

Kai Zheng
  • 6,640
  • 7
  • 43
  • 66
  • 1
    You can consider [this my solution for List](https://stackoverflow.com/a/62057285/12299030). It can be adapted for dynamic `ScrollView` as well. – Asperi May 28 '20 at 11:12

2 Answers2

27

The solution would be to have GeometryReader inside a .background/.overlay modifier. This makes it possible to read the height of the ScrollView content.

struct ContentView: View {

    var body: some View {
        ScrollView {
            ForEach(0..<1000) { i in
                Text("\(i)")
            }
            .background(
                GeometryReader { proxy in
                    Color.clear.onAppear { print(proxy.size.height) }
                }
            )
        }
    }
}

We get an output of 20500.0 which is correct.

Kai Zheng
  • 6,640
  • 7
  • 43
  • 66
-1

You can use a GeometryReader :

 ScrollView {
        GeometryReader { geometry in
         //print(geometry.size.height) 
       }
    }
CZ54
  • 5,488
  • 1
  • 24
  • 39