Created
June 3, 2022 17:06
-
-
Save zrxq/d43eb8abcfe454a47cab9030d32bf773 to your computer and use it in GitHub Desktop.
SwiftUI Scroll View scroll offset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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