iosswiftswiftui

SwiftUI - How to get size (height) of ScrollView content


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!


Solution

  • 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.