swiftuiscrollviewswiftui-scrollview

SwiftUI - How to get ScrollView Content Height after once the inside content is changed in Run time


I am able to print scrollview content height based on the below code when the countvalue is static

struct ContentView: View {

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

But when i Updated countValue in runtime, I not able to print the new scrollview contentsize height

Please Refer the Below Code

struct ContentCountView: View {

@State var countValue : Int = 100
    var body: some View {
        ScrollView {
            ForEach(0..<countValue, id: \.self) { i in
                HStack{
                    Text("\(i)")
                    Button("update"){
                        countValue = 150
                    }
                }
                
            }
            .background(
                GeometryReader { proxy in
                    Color.clear.onAppear {
                        print(proxy.size.height)
                        
                    }
                }
            )
        }
    }
}

how can I get the new scrollview content size height? Please explain.


Solution

  • proxy.size.height is updating, putting the print statement in onAppear just limits the printing to when it first appears. Try this:

    .background(
        GeometryReader { proxy in
             let _ = print(proxy.size.height)
             Color.clear
        }
    )