Skip to content

Instantly share code, notes, and snippets.

@zrxq
Created June 3, 2022 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zrxq/d43eb8abcfe454a47cab9030d32bf773 to your computer and use it in GitHub Desktop.
Save zrxq/d43eb8abcfe454a47cab9030d32bf773 to your computer and use it in GitHub Desktop.
SwiftUI Scroll View scroll offset
import SwiftUI
struct OffsetPreferenceKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
struct ContentView: View {
@State var offset = CGFloat(-1)
var body: some View {
VStack {
Spacer()
ScrollView(.horizontal, showsIndicators: false) {
ZStack() {
LazyHStack {
ForEach(0...24, id: \.self) { idx in
Text("\(idx)")
.background(.yellow)
}
}
GeometryReader { geo in
Color.clear.preference(key: OffsetPreferenceKey.self, value: geo.frame(in: .named("sv")).minX)
}
}
}
.coordinateSpace(name: "sv")
.onPreferenceChange(OffsetPreferenceKey.self) { offset in
self.offset = offset
}
Spacer()
Text("Offset: \(offset)")
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment