Advertisement
Milotronik

Scroll offset

Oct 1st, 2024
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.98 KB | None | 0 0
  1. import SwiftUI
  2.  
  3. struct ContentView: View {
  4.     @State private var scrollOffset: CGFloat = 0
  5.  
  6.     var body: some View {
  7.         ScrollView {
  8.             GeometryReader { geometry in
  9.                 Color.clear
  10.                     .preference(key: ScrollOffsetPreferenceKey.self, value: geometry.frame(in: .global).minY)
  11.             }
  12.             .frame(height: 0)
  13.            
  14.             VStack {
  15.                 ForEach(0..<100) { index in
  16.                     Text("Item \(index)")
  17.                         .padding()
  18.                 }
  19.             }
  20.         }
  21.         .onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
  22.             scrollOffset = value
  23.             print("Scroll offset: \(scrollOffset)")
  24.         }
  25.     }
  26. }
  27.  
  28. struct ScrollOffsetPreferenceKey: PreferenceKey {
  29.     typealias Value = CGFloat
  30.     static var defaultValue: CGFloat = 0
  31.     static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
  32.         value = nextValue()
  33.     }
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement