0

I'm trying to get scroll offset by placing GeometryReader inside of ScrollView but it disabled scroll (LazyVStack's area bounces back on scroll attempt). It seems like GeometryReader takes exactly the same size as LazyVStack and LazyVStack has .infinite height and therefore scroll doesn't work.

I tried placing GeometryReader around ScrollView and scroll works good but i don't receive any data from onPreferenceChange. Is there any workaround to make them both (scroll & onPreferenceChange reporting) work?

enter image description here

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack {
            ScrollView {
                GeometryReader { insideProxy in
                    LazyVStack(spacing: 0) {
                        ForEach(0...100, id:\.self) { val in
                            ZStack {
                                Text("test")
                                    .font(.system(size: 128))
                                
                            } // ZStack
                            .background(Color.blue)
                        } // ForEach
                        .background(Color.yellow)
                    }.preference(
                        key: OffsetPreferenceKey.self,
                        value: insideProxy.frame(in: .global).minY
                    )
                    .background(Color.red)
                }
            }
            .padding(.top, 40)
        }
        .onPreferenceChange(OffsetPreferenceKey.self) { newValue in
            print("The new value is: \(newValue)")
        }
        
        
    }
}


private struct OffsetPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = .zero
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {}
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
eugene_prg
  • 948
  • 2
  • 12
  • 25

0 Answers0