简体   繁体   中英

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!

Here is a way to actually get the height of the ScrollView content.

CZ54s answer seems intuitive, but it always returns a height of 10 which is not correct..

We have to read the height of the content instead. GeometryReader directly inside ScrollView doesn't do that. A possible approach would be with .background / .overlay .

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.

You can use a GeometryReader :

 ScrollView {
        GeometryReader { geometry in
         //print(geometry.size.height) 
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM